由于返回的字段不同,我正在努力反序列化下面的 JSON 片段,例如在配置中,它可以与 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"
将缺失的属性转换为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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句