4

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"
        },
      }
}
bbs_chad
  • 75
  • 1
  • 6
  • possible duplicate of [How can I parse a JSON string that would cause illegal C# identifiers?](http://stackoverflow.com/questions/24536533/how-can-i-parse-a-json-string-that-would-cause-illegal-c-sharp-identifiers) – Brian Rogers Jul 23 '14 at 03:14
  • Do you control this json? It is a poorly defined contract. You would be better off formatting it as an array than an object. `"devices" : [ { "name":"xxx", "id": "00-00-00-00-00" }, { "name":"xxx", "id": "00-00-00-00-01" }]` and so on – Rhys Bevilaqua Jul 23 '14 at 03:20

2 Answers2

9

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
Michael Liu
  • 52,147
  • 13
  • 117
  • 150
4

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);
WorkSmarter
  • 3,738
  • 3
  • 29
  • 34
Rhys Bevilaqua
  • 2,102
  • 17
  • 20