【问题标题】:Deserializing JSON when key values are unknown当键值未知时反序列化 JSON
【发布时间】:2014-07-23 02:53:01
【问题描述】:

如何在 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"
        },
      }
}

【问题讨论】:

标签: c# json json.net


【解决方案1】:

您可以使用字典将 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

【讨论】:

    【解决方案2】:

    根据这里的答案,https://stackoverflow.com/a/1212115/1465593json.net 会很容易地为你做这件事。

    看起来像这样:

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

    然后这样做

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 2015-03-23
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多