Deserialize json with Json.NET

烂漫一生 提交于 2019-12-11 12:48:39

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/16517734/deserialize-json-with-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!