[英]How to deserialize nested json
I have two APIs: 我有两个API:
GetDeviceInfo(string addr)
, which returns JSON data for a single device as follows: GetDeviceInfo(string addr)
,它返回单个设备的JSON数据,如下所示:
{ "DeviceName": "TCatPlcCtrl", "TurbineName": "WTG2", "State": "run", "TurbineType": "1500", "Version": "2.11.1816" }
GetAllDeviceInfo()
, which returns a collection of device data with IP addresses: 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" } }
For API GetDeviceInfo(string addr)
, I have tried NewtonSoft.Json and got correct data by calling JsonConvert.DeserializeObject<ModelClass>(content)
. 对于API GetDeviceInfo(string addr)
,我尝试了NewtonSoft.Json并通过调用JsonConvert.DeserializeObject<ModelClass>(content)
获得了正确的数据。
But I dont know how to deserialize nested JSON data returned by the GetAllDeviceInfo()
API. 但是我不知道如何反序列化由GetAllDeviceInfo()
API返回的嵌套JSON数据。
Assuming your model class is defined like this: 假设您的模型类的定义如下:
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; }
}
Then, for the first JSON, you can deserialize like this: 然后,对于第一个JSON,您可以像这样反序列化:
var device = JsonConvert.DeserializeObject<DeviceInfo>(json);
And for the second case, you can deserialize to a dictionary, where the keys are the IP addresses, and the values are the devices: 对于第二种情况,您可以反序列化为字典,其中的键是IP地址,值是设备:
var dict = JsonConvert.DeserializeObject<Dictionary<string, DeviceInfo>>(json2);
Demo fiddle: https://dotnetfiddle.net/Hs9OJo 演示小提琴: https : //dotnetfiddle.net/Hs9OJo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.