2017-08-25 148 views
0

我有两个API:如何反序列化嵌套的JSON

  1. GetDeviceInfo(string addr),返回JSON数据,单台设备如下:

    { 
        "DeviceName": "TCatPlcCtrl", 
        "TurbineName": "WTG2", 
        "State": "run", 
        "TurbineType": "1500", 
        "Version": "2.11.1816" 
    } 
    
  2. GetAllDeviceInfo(),返回设备的数据的集合IP地址:

    { 
        "192.168.151.1": { 
        "DeviceName": "TCatPlcCtrl", 
        "TurbineName": "WTG2", 
        "State": "run", 
        "TurbineType": "1500", 
        "Version": "2.11.1816" 
        }, 
        "192.168.151.33": { 
        "DeviceName": "TCatPlcCtrl", 
        "TurbineName": "WTG2", 
        "State": "stop", 
        "TurbineType": "1500", 
        "Version": "2.11.2216" 
        } 
    } 
    

对于API GetDeviceInfo(string addr),我试过了NewtonSoft.Json,并通过调用JsonConvert.DeserializeObject<ModelClass>(content)得到了正确的数据。

但我不知道如何反序列化GetAllDeviceInfo() API返回的嵌套JSON数据。

+0

同样的道理?它仍然只是一个对象,只是一个更复杂的对象。 –

+0

这是一个字典<字符串,模型类型>类型.. – Bob

回答

1

假设你的模型类的定义是这样的:

public class DeviceInfo 
{ 
    public string DeviceName { get; set; } 
    public string TurbineName { get; set; } 
    public string State { get; set; } 
    public string TurbineType { get; set; } 
    public string Version { get; set; } 
} 

然后,第一JSON,你可以反序列化这样的:

var device = JsonConvert.DeserializeObject<DeviceInfo>(json); 

而对于第二种情况,你可以反序列化到一个字典,其中键是IP地址,值是设备:

var dict = JsonConvert.DeserializeObject<Dictionary<string, DeviceInfo>>(json2); 

Demo小提琴:https://dotnetfiddle.net/Hs9OJo

+0

谢谢。虽然没有尝试过,我确定它的工作原理。 – Bob