Search code examples
c#json.netphilips-hue

Deserialize json with Json.NET


I have JSON that looks like this (from the Philips HUE API):

{
    "1": {"name": "Bedroom"},
    "2": {"name": "Kitchen"}
}

When I try to deserialize this document I run into problems because the document is structured the way it is.

If it had been formated like this:

[
   {"nr": "1", "name": "Bedroom"},
   {"nr": "2", "name": "Kitchen"}
]

Everything would have been fine. Now I am forced to do string parsing in order to extract the data... :-(

Any ideas or suggestions?


Solution

  • I would deserialize to JObject and use it as Dictionary

    var jObj = (JObject)JsonConvert.DeserializeObject(json);
    Console.WriteLine(jObj["1"]["name"]);
    

    or

    dynamic jObj = JsonConvert.DeserializeObject(json);
    Console.WriteLine(jObj["1"].name);