JSON.NET反序列化对象/对象数组中的对象

时间:2012-06-03 09:49:45

标签: json.net

我遇到的情况是我正在使用的API返回不一致的JSON,我想使用JSON.NET反序列化。在一种情况下,它返回一个包含对象的对象(注意外部“1”可以是任何数字):

{
   "1":{
      "0":{
         "db_id":"12835424",
         "title":"XXX"
      },
      "1":{
         "db_id":"12768978",
         "title":"YYY"
      },
      "2":{
         "db_id":"12768980",
         "title":"ZZZ"
      },
      "3":{
         "db_id":"12768981",
         "title":"PPP"
      }
   }
}

在另一种情况下,它返回一个对象数组:

{
   "3":[
      {
         "db_id":"12769199",
         "title":"XXX"
      },
      {
         "db_id":"12769200",
         "title":"YYY"
      },
      {
         "db_id":"12769202",
         "title":"ZZZ"
      },
      {
         "db_id":"12769243",
         "title":"PPP"
      }
   ]
}

我不知道为什么会出现这种不一致,但这是我正在使用的格式。使用JsonConvert.DeserializeObject方法对这两种格式进行反序列化的正确方法是什么?

2 个答案:

答案 0 :(得分:11)

使用当前版本的Json.NET(Json.NET 4.5 Release 11),这里有一个 CustomCreationConverter ,它将处理Json,它有时会反序列化为对象,有时也会反序列化为数组。

public class ObjectToArrayConverter<T> : CustomCreationConverter<List<T>> where T : new() 
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        List<T> target = new List<T>();

        try
        {
            // Load JObject from stream
            JArray jArray = JArray.Load(reader);

            // Populate the object properties
            serializer.Populate(jArray.CreateReader(), target);
        }
        catch (JsonReaderException)
        {
            // Handle case when object is not an array...

            // Load JObject from stream
            JObject jObject = JObject.Load(reader);

            // Create target object based on JObject
            T t = new T();

            // Populate the object properties
            serializer.Populate(jObject.CreateReader(), t);

            target.Add(t);
        }

        return target;
    }

    public override List<T> Create(Type objectType)
    {
        return new List<T>();
    }
}

示例用法:

[JsonObject]
public class Project
{
    [JsonProperty]
    public string id { get; set; }

    // The Json for this property sometimes comes in as an array of task objects, 
    // and sometimes it is just a single task object.
    [JsonProperty]
    [JsonConverter(typeof(ObjectToArrayConverter<Task>))]
    public List<Task> tasks{ get; set; }
}

[JsonObject]
public class Task
{
    [JsonProperty]
    public string name { get; set; }

    [JsonProperty]
    public DateTime due { get; set; }
}

答案 1 :(得分:2)

我认为通过创建 JsonCreationConverter 应该可以做到这一点。本文可能会有所帮助:http://dotnetbyexample.blogspot.nl/2012/02/json-deserialization-with-jsonnet-class.html