反序列化JSON

时间:2017-03-10 15:32:49

标签: c# json

由于返回了不同的字段,我很难对下面的JSON片段进行反序列化,例如在config中,它适用于config.on,因为这是在每个配置块中,但是因为它们都是不同的,我怎么绕这个? JSON返回所有连接的不同传感器,以便使用不同的字段。

dynamic obj = JsonConvert.DeserializeObject(response);
//
foreach (var item in obj)
{
    string temperature = item.ToString();         //this shows the full object in text
    //    Debug.WriteLine(temperature);           //this shows the full object in text

    dynamic group = item;

    string idstring = group.Name.ToString();

    foreach (var prop in group)
    {
        string name = prop.name; 
        string temp = prop.config.on;
        //string temp = prop.state.lastupdated;
        //string temp = prop.swversion;

        //Debug.WriteLine(temp);

        string namestring = name.ToString();
        string tempstring = temp.ToString();

        arr[0] = idstring.ToLower();
        arr[1] = namestring.ToLower();
        arr[2] = tempstring.ToLower();

部分JSON响应

{
    "1": {
        "state": {
            "daylight": true,
            "lastupdated": "2017-03-10T07:01:00"
        },
        "config": {
            "on": true,
            "configured": true,
            "sunriseoffset": 30,
            "sunsetoffset": -30
        },
        "name": "Daylight",
        "type": "Daylight",
        "modelid": "PHDL00",
        "manufacturername": "Philips",
        "swversion": "1.0"
    },
    "2": {
        "state": {
            "temperature": 1830,
            "lastupdated": "2017-03-10T08:11:51"
        },
        "config": {
            "on": true,
            "battery": 100,
            "reachable": true,
            "alert": "none",
            "ledindication": false,
            "usertest": false,
            "pending": [

},
"name": "Hall",
"type": "ZLLPresence",
"modelid": "SML001",
"manufacturername": "Philips",
"swversion": "6.1.0.18912",
"uniqueid": "00:17:88:01:02:01:8b:be-02-0406"
  },
 "4": {
    "state": {
  "lightlevel": 12270,
  "dark": true,
  "daylight": false,
  "lastupdated": "2017-03-10T08:14:28"
},
"config": {
  "on": true,
  "battery": 100,
  "reachable": true,
  "alert": "none",
  "tholddark": 16011,
  "tholdoffset": 7000,
  "ledindication": false,
  "usertest": false,
  "pending": [

  ]
},
"name": "Hue ambient light sensor 1",
"type": "ZLLLightLevel",
"modelid": "SML001",
"manufacturername": "Philips",
"swversion": "6.1.0.18912",
"uniqueid": "00:17:88:01:02:01:8b:be-02-0400"
  },
  "5": {
"state": {
  "temperature": 1919,
  "lastupdated": "2017-03-10T08:12:50"

1 个答案:

答案 0 :(得分:0)

将遗失的属性多次转换为String,无需额外的广告素材。所以不要这样做:

string namestring = name.ToString();
string tempstring = temp.ToString();

您只需预先检查null条件(如果需要)并采取相应措施。如果缺少某个属性,Json.NET不会抛出异常,因此您可以尝试获取所需的所有字段,然后相应地执行业务逻辑:

string name = prop.name;
string temp = prop.config.on;
string battery = prop.config.battery;
if (battery == null) 
    // maybe throw exception, maybe assign default value; whatever fits you