C#

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.

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago