在 JSON 对象中搜索节点

本文关键字:搜索 节点 对象 JSON | 更新日期: 2023-09-27 18:33:00

>我有一个大的json对象,当我想在json对象中搜索特定节点时,我得到了nullpointerexception,因为该null不存在,我的json是这样的

"InternetGatewayDevice": {
  "DeviceSummary": {
    "_value": "InternetGatewayDevice:1.1[](Baseline:1, DeviceAssociation:1, Time:1, QoS:1, Bridging:1, IPPing:1, USBLAN:1, WiFiLAN:1, GponWAN:1), VoiceService:1.0[1](Endpoint:1, SIPEndpoint:1)",
    "_timestamp": "2014-12-01T09:07:09.943Z",
    "_type": "xsd:string"
  },
  "DeviceInfo": {
    "SpecVersion": {
      "_value": "1.0",
      "_timestamp": "2014-12-01T09:07:09.943Z",
      "_type": "xsd:string"
    },
    "HardwareVersion": {
      "_value": "V1.0",
      "_timestamp": "2014-12-01T09:07:09.943Z",
      "_type": "xsd:string"
    },
    "SoftwareVersion": {
      "_value": "V1.1",
      "_timestamp": "2014-12-01T09:07:09.943Z",
      "_type": "xsd:string"
    },
    "ProvisioningCode": {
      "_value": "",
      "_timestamp": "2014-12-01T09:07:09.943Z",
      "_type": "xsd:string"
    }
  },
  "ManagementServer": {
    "ConnectionRequestURL": {
      "_value": "xxxxxx",
      "_timestamp": "2014-12-01T09:07:09.943Z",
      "_type": "xsd:string"
    },
    "ParameterKey": {
      "_value": "",
      "_timestamp": "2014-12-01T09:07:09.943Z",
      "_type": "xsd:string"
    }
  },
  "WANDevice": {
    "1": {
      "WANConnectionDevice": {
        "10": {
          "WANPPPConnection": {
            "1": {
              "ExternalIPAddress": {
                "_value": "xxxxxx",
                "_timestamp": "2014-12-01T09:07:09.943Z",
                "_type": "xsd:string"
              },
              "Username": {
                "_value": "xxxxxxxx",
                "_timestamp": "2014-12-01T09:07:09.943Z",
                "_type": "xsd:string"
              }
            }
          }
        }
      }
    }
  }
}

我搜索这个LANDevice,我用这段代码搜索节点::

JArray deviceJArray = JArray.Parse(jsonResult);
var strAuthModeBasic = deviceJArray[0]["InternetGatewayDevice"]["LANDevice"]["InternetGatewayDevice"]["LANDevice"]["1"]["WLANConfiguration"]["1"]["BeaconType"]["_value"].ToString();

我想处理这个例外。

在 JSON 对象中搜索节点

我会通过将 json 序列化为 c# 复杂对象来做到这一点,您可以在其中进行空检查。收到错误的原因是,您正在为变量分配一个不存在的值。

这是Microsoft的序列化示例(如果它来自服务):http://msdn.microsoft.com/en-us/library/bb412179%28v=vs.110%29.aspx

或者,如果您只想序列化已有的 JSON 字符串,请使用 JavaScriptSerializer:http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx

我用了一些类似的东西,但在JS中。

请注意,我还没有测试过。基本上:遍历对象,遇到缺少的步骤时返回 null。如果您设法找到实际的主对象,则返回所需的值。

var path = "path.to.your.object"; // instead of array["path"]["to"]["your"]["object"]
var fieldName = "_value";
array.Get(path, fieldName);
public static string Get(this JArray a, string path, string fieldName){
    // isnullorempty path -> return null
    var steps = path.Split(".");
    JArray obj = a;
    for(var i = 0; i < steps.length; ++i){
        obj = obj[steps[i]];
        if(obj == null) return null;
    }
    return obj[fieldName];
}