在键值未知时反序列化JSON

时间:2014-07-23 02:53:02

标签: c# json json.net

如何在C#中使用JSON.net反序列化JSON,其中键值未知(它们是多个设备的MAC地址)。可能有一个或多个密钥条目。

{
    "devices":
    {
        "00-00-00-00-00-00-00-00":
        {
            "name":"xxx",
            "type":"xxx",
            "hardwareRevision":"1.0",
            "id":"00-00-00-00-00-00-00-00"
        },
        "01-01-01-01-01-01-01-01":
        {
            "name":"xxx",
            "type":"xxx",
            "hardwareRevision":"1.0",
            "id":"01-01-01-01-01-01-01-01"
        },
      }
}

2 个答案:

答案 0 :(得分:6)

您可以使用Dictionary将MAC地址存储为键:

public class Device
{
    public string Name { get; set; }
    public string Type { get; set; }
    public string HardwareRevision { get; set; }
    public string Id { get; set; }
}

public class Registry
{
    public Dictionary<string, Device> Devices { get; set; }
}

以下是您可以反序列化样本JSON的方法:

Registry registry = JsonConvert.DeserializeObject<Registry>(json);

foreach (KeyValuePair<string, Device> pair in registry.Devices)
{
    Console.WriteLine("MAC = {0}, ID = {1}", pair.Key, pair.Value.Id);
}

输出:

MAC = 00-00-00-00-00-00-00-00, ID = 00-00-00-00-00-00-00-00
MAC = 01-01-01-01-01-01-01-01, ID = 01-01-01-01-01-01-01-01

答案 1 :(得分:3)

根据这里的答案https://stackoverflow.com/a/1212115/1465593 json.net将很容易为你做到这一点

看起来像这样:

public class Contract 
{
    public IDictionary<string, Device> Devices { get; set; }
}

然后就这样做

var result = JsonConvert.DeserializeObject<Contract>(myJson);