在键值未知(它们是多个设备的MAC地址)的情况下,如何在C#中使用JSON.net反序列化JSON。可能有一个或多个关键条目。
{ "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地址存储为密钥:
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