[英]How can deserialize using Newtonsoft.Json?
How to read it using Newtonsoft.Json? 如何使用Newtonsoft.Json读取它?
{
"192.168.0.12":
{
"Name":"12",
"Mode":"STOP"
},
"192.168.0.13":
{
"Name":"13",
"Mode":"STOP"
}
}
I am using this data class as below: 我正在使用以下数据类:
class Device{
public string Name;
public string Mode;
}
Dictionary<string, Device> devices;
So, I tried this code to deserialize. 因此,我尝试使用此代码反序列化。 But, I can't read value from JToken as dictionary.
但是,我无法从JToken读取值作为字典。
JObject JDevices = JObject.Parse(Encoding.ASCII.GetString(buffer));
foreach (JProperty property in JDevices.Properties())
{
string name = property.Name;
JToken value = property.Value;
// to read Device.Name and Device.Mode
}
You can use dynamic object var result = JsonConvert.DeserializeObject<dynamic>(json);
您可以使用动态对象
var result = JsonConvert.DeserializeObject<dynamic>(json);
Code to convert to Dictionary: 转换成字典的代码:
Dictionary<string, Device> devices = new Dictionary<string, Device>();
string json = "{\"192.168.0.12\": {\"Name\":\"12\",\"Mode\":\"STOP\"},\"192.168.0.13\": {\"Name\":\"13\",\"Mode\":\"STOP\"}}";
var result = JsonConvert.DeserializeObject<dynamic>(json);
foreach (var item in result)
{
var name = item.Name;
evices.Add(item.Name.ToString(), new Device {Name = item.Value.Name.ToString(), Mode = item.Value.Mode.ToString()});
}
Try this, no need to use dynamic. 试试这个,不需要使用动态的。
var json = "{
"192.168.0.12":
{
"Name":"12",
"Mode":"STOP"
},
"192.168.0.13":
{
"Name":"13",
"Mode":"STOP"
}
}";
var result = JsonConvert.DeserializeObject<Dictionary<string, Device>>(json);
foreach (var device in result.Values)
{
var name = device.Name;
var mode = device.Mode;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.