Deserializing JSON when key values are unknown
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"
},
}
}
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; }
}
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);
}
Output:
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
According to the answer here, https://stackoverflow.com/a/1212115/1465593 json.net will do this for you pretty easily.
It would look something like this:
public class Contract
{
public IDictionary<string, Device> Devices { get; set; }
}
Then do this
var result = JsonConvert.DeserializeObject<Contract>(myJson);