3

I have a situation where an API I'm using is returning inconsistent JSON, which I want to deserialize using JSON.NET. In one case, it returns an object that contains objects (note that the outer "1" can be any number):

{
   "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"
      }
   }
}

And in another case, it returns an array of objects:

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

I have no idea why this inconsistency exists, but this is the format I'm working with. What would be the correct way to deserialize both formats with the JsonConvert.DeserializeObject method?

2 Answers 2

13

With the current version of Json.NET (Json.NET 4.5 Release 11), here is a CustomCreationConverter that will handle Json that deserializes sometimes as an object and sometimes as an array.

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>();
    }
}

Example Usage:

[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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This should be the accepted answer. Precise and fully functional plug and play. Thanks.
2

I think this is something that should be possible by creating a JsonCreationConverter. This article can probably help out: http://dotnetbyexample.blogspot.nl/2012/02/json-deserialization-with-jsonnet-class.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.