本文介绍了用Json.NET反序列化json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的JSON(来自Philips HUE API):

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.

如果其格式如下:

[
   {"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... :-(

有什么想法或建议吗?

推荐答案

我将反序列化为JObject并将其用作Dictionary

I would deserialize to JObject and use it as Dictionary

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

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

这篇关于用Json.NET反序列化json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:31
查看更多