如何使用Newtonsoft.Json反序列化?

时间:2019-04-28 16:20:58

标签: c# json json.net

如何使用Newtonsoft.Json阅读它?

{
  "192.168.0.12": 
       {
         "Name":"12",
         "Mode":"STOP"
       },
  "192.168.0.13": 
       {
         "Name":"13",
         "Mode":"STOP"
       }
}

我正在使用以下数据类:

class Device{
    public string Name;
    public string Mode;
}

Dictionary<string, Device> devices;

因此,我尝试使用此代码反序列化。但是,我无法从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
}

2 个答案:

答案 0 :(得分:1)

您可以使用动态对象var result = JsonConvert.DeserializeObject<dynamic>(json);

要转换为字典的代码:

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()});

 }

答案 1 :(得分:0)

尝试一下,无需使用动态。

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;
}