1

我想反序列化这样的 JSON 字符串

{
   "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":[]
}

当试图反序列化引发异常时,因为需要一个数组来解析“列表”,但我的对象有一个 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 并“手动”进行映射的情况下处理此问题?

4

1 回答 1

1

一个简单的解决方法是在反序列化之前执行此操作:

yourString = yourString.Replace("\"list\":[]", "\"list\":{}");
于 2012-06-01T22:49:48.057 回答