Deserialize an array inside a json object using JsonConvert.DeserializeObject()

Viewed 913

I have a requirement where I have incoming json object of the following format:

{
   "CustomerList": {
       "Customer": [{
            "CustomerCode" : "C123",
            "CustomerName" : "Peter"
       },
       {
            "CustomerCode" : "C456",
            "CustomerName" : "John"
       }]
   }
}

And I have the my C# object of the following Format:

[System.Xml.Serialization.XmlArrayItemAttribute(IsNullable = "false")]
public Customer[] CustomerList
{
   get; set;
}

[System.Xml.Serialization.XmlTypeAttribute()]
public class Customer
{
    public string CustomerCode {get; set;}
    public string CustomerName {get; set;}
}

During Deserialization using JsonConvert.DeserializeObject(), I get the following error: Cannot deserialize the current JSON object into type Customer[], because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

On my side the limitation is that I cannot change the incoming JSON object and neither can I modify the C# object structure. So the ask is that, is there a way to map the Customer node in the incoming Json, to the CustomerList C# array directly, without needing to rename or change the structure of either?

2 Answers

To deserialize the JSON object you need to create a similar C# class.

public class JsonObjectTest {
    [JsonPropertyName("CustomerList")]
    public Customer CustomerPreList {get;set;}
}

public class Customer {
    public List<CustomerObject> Customer {get;set;}
}

public class CustomerObject {

    public string CustomerCode { get; set; }
    public string CustomerName { get; set; }
}

Afterwards you deserialize the JSON object:

CustomerList xmlData = JsonConvert.DeserializeObject<JsonObjectTest>(jsonObjectString).Select(data => 
    new CustomerList = data.CustomerPreList.toArray());

Unfortunately I could not ask you if you have a permission to create new classes (I need more points). If this is the case try AutoMapper to create a mapping policy for this specific case.

Happy coding :)

Based on the JSON you have shared, you need to have following class structure.

public class Customer    {
    public string CustomerCode { get; set; } 
    public string CustomerName { get; set; } 
}

public class CustomerList    {
    public List<Customer> Customer { get; set; } 
}

public class RootObject  {
    public CustomerList CustomerList { get; set; } 
}

and then you need to deserizalize the JSON as following.

RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonString);

Here jsonString is the string variable which has the JSON string.

I hope you this will help you resolve your issue.

Related