2012-06-03 207 views
1

我有一種情況,我正在使用的API返回不一致的JSON,我想使用JSON.NET反序列化。在一種情況下,它返回一個包含對象的對象(注意的是,外「1」可以是任意數量):JSON.NET反序列化對象/對象數組中的對象

{ 
    "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方法反序列化兩種格式的正確方法是什麼?

回答

11

隨着Json.NET(Json.NET 4.5發行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; } 
}