使用JSON.NET反序列化任意JSON对象

时间:2012-06-01 22:30:57

标签: c# silverlight windows-phone-7 json.net

我想反序列化像这样的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并“手动”进行映射的情况下处理此问题?

1 个答案:

答案 0 :(得分:1)

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

yourString = yourString.Replace("\"list\":[]", "\"list\":{}");