当键值未知时反序列化 JSON

Deserializing JSON when key values are unknown(当键值未知时反序列化 JSON)
本文介绍了当键值未知时反序列化 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

How do I deserialize JSON with JSON.net in C# where the key values are not known (they are MAC addresses of multiple devices). There could be one or more key entries.

{
    "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"
        },
      }
}

推荐答案

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

You can use a Dictionary to store the MAC addresses as keys:

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 的方法:

Here's how you could deserialize your sample 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

这篇关于当键值未知时反序列化 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean(强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或布尔值)
Using JSON to Serialize/Deserialize TimeSpan(使用 JSON 序列化/反序列化 TimeSpan)
Could not determine JSON object type for type quot;Classquot;(无法确定类型“Class的 JSON 对象类型.)
How to deserialize a JSONP response (preferably with JsonTextReader and not a string)?(如何反序列化 JSONP 响应(最好使用 JsonTextReader 而不是字符串)?)
how to de-serialize JSON data in which Timestamp it-self contains fields?(如何反序列化时间戳本身包含字段的JSON数据?)
JSON.Net custom contract serialization and Collections(JSON.Net 自定义合约序列化和集合)