Deserializing JSON when key values are unknown

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

Leave a Comment