[英]How to deserialize nested json
我有两个API:
GetDeviceInfo(string addr)
,它返回单个设备的JSON数据,如下所示:
{ "DeviceName": "TCatPlcCtrl", "TurbineName": "WTG2", "State": "run", "TurbineType": "1500", "Version": "2.11.1816" }
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数据。
假设您的模型类的定义如下:
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);
演示小提琴: https : //dotnetfiddle.net/Hs9OJo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.