Reputation: 107
I have two APIs:
GetDeviceInfo(string addr)
, which returns JSON data for a single device as follows:
{
"DeviceName": "TCatPlcCtrl",
"TurbineName": "WTG2",
"State": "run",
"TurbineType": "1500",
"Version": "2.11.1816"
}
GetAllDeviceInfo()
, which returns a collection of device data with IP addresses:
{
"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)
.
But I dont know how to deserialize nested JSON data returned by the GetAllDeviceInfo()
API.
Upvotes: 0
Views: 1350
Reputation: 129657
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:
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:
var dict = JsonConvert.DeserializeObject<Dictionary<string, DeviceInfo>>(json2);
Demo fiddle: https://dotnetfiddle.net/Hs9OJo
Upvotes: 1