Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON when key values are unknown

Tags:

json

c#

json.net

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"
        },
      }
}
like image 532
bbs_chad Avatar asked Dec 14 '22 21:12

bbs_chad


2 Answers

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
like image 142
Michael Liu Avatar answered Jan 03 '23 01:01

Michael Liu


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);
like image 29
Rhys Bevilaqua Avatar answered Jan 03 '23 00:01

Rhys Bevilaqua