在json对象中搜索节点

时间:2014-12-04 09:21:25

标签: c# json json.net

我有一个大的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();

我想要处理这个例外。

2 个答案:

答案 0 :(得分:1)

我会通过将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

答案 1 :(得分:0)

我使用了simillar,但在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];
}