问题描述
我耗费返回JSON结果包裹'D'根元素中的WCF服务。 JSON响应看起来是这样的:
I'm consuming a WCF service that returns JSON results wrapped inside the 'd' root element. The JSON response looks like this:
{"d":[
{
"__type":"DiskSpaceInfo:#Diagnostics.Common",
"AvailableSpace":38076567552,
"Drive":"C:\\",
"TotalSpace":134789197824
},
{
"__type":"DiskSpaceInfo:#Diagnostics.Common",
"AvailableSpace":166942183424,
"Drive":"D:\\",
"TotalSpace":185149157376
}
]}
我不想使用动态类型,我有我想要反序列化时使用我的课Diagnostics.Common.DiskSpaceInfo。
I don't want to use dynamic typing, I have my class Diagnostics.Common.DiskSpaceInfo that I want to use when deserializing.
我使用Json.NET(Netwonsoft JSON )。
I am using Json.NET (Netwonsoft JSON).
现在的问题是如何分辨它忽略根元素(即D元素)和解析里面是什么。
The question is how to tell it to ignore the root element (that 'd' element) and parse what is inside.
最好的解决方案我至今是使用匿名类型:
The best solution I have so far is to use an anonymous type:
DiskSpaceInfo[] result = JsonConvert.DeserializeAnonymousType(json, new
{
d = new DiskSpaceInfo[0]
}).d;
这确实可以工作,但我不很喜欢。有另一种方式?我想是这样的:
this actually works but I don't like it very much. Is there another way? What I would like is something like:
DiskSpaceInfo[] result = JsonConvert.Deserialize(json, skipRoot: true);
或类似的东西...
推荐答案
如果您知道在这种情况下,如搜索,这是一个根节点那么你可以做以下D。
If you know what to search like in this case "d" which is a root node then you can do the following.
JObject jo = JObject.Parse(json);
DiskSpaceInfo[] diskSpaceArray = jo.SelectToken("d", false).ToObject<DiskSpaceInfo[]>();
如果您只是想忽略根类,你不知道,那么你可以使用@ GIU待办事项解决方案,这一点你可以使用 test2.ToObject< DiskSpaceInfo []>();
而不是 Console.Write(测试2);
If you simply want to ignore the root class which you do not know then you can use the "@Giu Do" solution just that you can use test2.ToObject<DiskSpaceInfo[]>();
instead of the Console.Write(test2);
JObject o = JObject.Parse(json);
if (o != null)
{
var test = o.First;
if (test != null)
{
var test2 = test.First;
if (test2 != null)
{
DiskSpaceInfo[] diskSpaceArray = test2.ToObject<DiskSpaceInfo[]>();
}
}
}
这篇关于反序列化JSON - 如何忽略根元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!