【发布时间】:2016-12-30 08:42:01
【问题描述】:
我在使用 newtonsoft json 反序列化 Json 时遇到问题。
我有课
[Serializable]
public class ValueAdd
{
[JsonProperty(PropertyName = "@id")]
public string Description { get; set; }
[JsonProperty(PropertyName = "@description")]
public string Id { get; set; }
}
[Serializable]
public class ValueAdds
{
public List<ValueAdd> ValueAdd { get; set; }
[JsonProperty(PropertyName = "@size")]
public string Size { get; set; }
}
API 返回愚蠢的两种格式:一个我可以正确序列化:
"ValueAdds":
{
"@size": "3",
"ValueAdd":
[
{
"@id": "2103",
"description": "some property"
},
{
"@id": "2192",
"description": "some property"
},
{
"@id": "2196",
"description": "some property"
}
]
}
但是当他们返回一个属性时,它并没有返回一个列表.. 只能以这种方式返回:
"ValueAdds":
{
"@size": "1",
"ValueAdd":
{
"@id": "2103",
"description": "some property"
}
}
导致我出现解析器错误
JsonConvert.DeserializeObject<ValueAdds>(_response);
Newtonsoft.Json.dll 中发生了“Newtonsoft.Json.JsonSerializationException”类型的第一次机会异常
附加信息:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[myproperty]',因为该类型需要 JSON 数组(例如 [ 1,2,3]) 正确反序列化。
我的问题是,有没有办法解决它?我无法更改 api 响应,我需要更改尝试解析是否有列表..
【问题讨论】:
-
json2csharp.com 可能会帮助您创建合适的模型
-
要获得适当的解决方案,您必须考虑使用
JsonConverter中解释的自定义another post 来处理这两种情况 -
使用来自How to handle both a single item and an array for the same property using JSON.net的
SingleOrArrayConverter<ValueAdd>。
标签: c# arrays json serialization json.net