我想像这样反序列化 JSON strin
{
"status":"1",
"since":"1245626956',
"list":{
"1":{
"item_id":"1"
},
"2":{
"item_id":"2"
}
}
}
为此,我有一个对象来解析
public class ListResponse
{
public String status { get; set; }
public String since { get; set; }
public IDictionary<String, Item> list { get; set; }
}
我用这句话:
ListResponse list = JsonConvert.DeserializeObject<ListResponse>(message);
这很好用,但我有一个问题,因为响应可能是这样的
{
"status":"1",
"since":"1245626956',
"list":[]
}
尝试反序列化时,会引发异常,因为需要一个数组来解析"list",但我的对象有一个 IDictionary。
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.IDictionary`2[System.String,Item]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
如何在不使用 Linq 获取 JObject 并"手动"进行映射的情况下处理此问题?
一个简单的解决方法是在反序列化之前执行此操作:
yourString = yourString.Replace(""list":[]", ""list":{}");