简体   繁体   English

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

[英]Deserialize arbitrary JSON object with JSON.NET

I want to deserialize a JSON strin like this 我想反序列化这样的JSON strin

{
   "status":"1",
   "since":"1245626956',
   "list":{
      "1":{
         "item_id":"1"
      },
      "2":{
         "item_id":"2"
      }
   }
}

For this I have an object that parses that 为此,我有一个对象来解析

public class ListResponse
{
    public String status { get; set; }
    public String since { get; set; }
    public IDictionary<String, Item> list { get; set; }
}

I use this sentence: 我用这句话:

ListResponse list = JsonConvert.DeserializeObject<ListResponse>(message);

That works well but I have a problem because response can be something like this 效果很好,但我有一个问题,因为响应可能是这样的

{
   "status":"1",
   "since":"1245626956',
   "list":[]
}

When trying to deserialize that an exception raises because needs an array to parse 'list' but my object has a IDictionary. 尝试反序列化时会引发异常,因为需要数组来解析“列表”,但是我的对象有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.

How can I handle this issue without using Linq to obtain JObject and do the mapping "by hand"? 如何在不使用Linq来获取JObject和“手动”映射的情况下处理此问题?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM