Deserialize Both Single Item And An Array For The Same Property In C#

In some scenarios, we are getting a dynamic response, for example, In the same property, we are getting a single element and sometimes an array of elements. That is a challenging task to handle both a single item and an array for the same property while deserializing. In this article, we will handle both item and array for the same property.

The easy and best way to handle this scenario is we should create a custom JsonConverter. To handle this I’ll use the Newtonsoft.Json package.

For example we are getting JSON as per the below class.

public class Orders
{
    [JsonConverter(typeof(ElementConverter<Item>))]
    public List<Item> Item { get; set; }
}

public class Item
{
    public string Name { get; set; }
    public string Description { get; set; }
}

Now, I’ll create one new class namely ElementConverter, It will generic so it can be used with any kind of data type.

public class ElementConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<T>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>();
        }
        return new List<T> { token.ToObject<T>() };
    }    

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

here is the code to deserialize JSON string.

var json = "JSON STRING"; 
var response = JsonConvert.DeserializeObject<T>(json);

And finally, you have done with it.

hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories