Deserializing JSON when key values are unknown(当键值未知时反序列化 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当键值未知时反序列化 JSON


基础教程推荐
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01