问题描述
我用的是DataContractJsonSerializer一个JSON字符串解析为对象hierarchie。
JSON字符串看起来是这样的:
I use the DataContractJsonSerializer to parse a json string into a object hierarchie.The json string looks like this:
{
"groups": [
{
"attributes": [
{
"sortOrder": "1",
"value": "A"
},
{
"sortOrder": "2",
"value": "B"
}
]
},
{
"attributes": {
"sortOrder": "1",
"value": "C"
}
}
]
}
正如你所看到的属性的分值可以是一个数组或一个单一的项目。
我发现那里的问题occures的code部分:
As you can see the sub value of "attributes" can be an array or a single item.I found the code part where the problem occures:
[DataContract]
public class ItemGroup
{
[DataMember(Name="attributes")]
public List<DetailItem> Items { get; set; }
}
这适用于第一个,但未能在第二个。
This works for the first one but fails on the second one.
有没有人回答这个?
THX
推荐答案
由于丹尼尔说,如果你能控制的Json的创作,不如继续如此。
但是,如果你不能,那么你可以使用Json.Net库&放大器;从JSONObject的类
this链接写一些code,如:
As Daniel said, if you can control the creation of Json, it is better to continue that way.But if you can't, then you can use Json.Net library & the JsonObject class fromthis link to write some code like:
JObject o = (JObject)JsonConvert.DeserializeObject(input);
dynamic json = new JsonObject(o);
foreach (var x in json.groups)
{
var attrs = x.attributes;
if (attrs is JArray)
{
foreach (var y in attrs)
{
Console.WriteLine(y.value);
}
}
else
{
Console.WriteLine(attrs.value);
}
}
这篇关于当值可以是一个数组或一个单一的项目C#DataContractJsonSerializer失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!