user1554650 user1554650 - 2 months ago 8
C# Question

Serializing Json to c# Class throwing error

I have a JSON returning from web like this

{
"data": {
"normal_customer": {
"0": {
"id": 1,
"name": "ALPHY"


}
},
"1": {
"id": 2,
"name": "STEVEN"

}

},
"luxury_customer": {
"3": {
"id": 8,
"name": "DEV"

}
}
}
}


I have created c# classes

public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}

public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }

[JsonProperty("name")]
public string name { get; set; }

public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}

public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}

public class RootObject
{
public Data data { get; set; }
}
}


When I use deserialize the response from the website using below c# code

var result1 = JsonConvert.DeserializeObject<Data>(response);


but result1.luxury_customers contains customerdetails which is null.

As suggested by @hellostone, I have modified to rootdata, then also
result1.luxury_customers contains customerdetails is null.

Any idea how to deserialize to c# class

When we pasted Json to visual studio, it generated classes as below

public class Rootobject
{
public Data data { get; set; }
}

public class Data
{
public Standard_Customers standard_Customers { get; set; }
public Luxury_Customers luxury_Customers { get; set; }
}

public class Standard_Customers
{
public _0 _0 { get; set; }
public _1 _1 { get; set; }
public _2 _2 { get; set; }
public _4 _4 { get; set; }
public _5 _5 { get; set; }
}

public class _0
{
public int id { get; set; }
public string name { get; set; }

}


individual classes are generated in standard customers , can we use list for this

Answer

I've managed to deserialize Json with this classes:

public class CustomersDetails
{
    [JsonProperty("id")]
    public int id { get; set; }
    [JsonProperty("name")]
    public string name { get; set; }
}

public class Data
{
    public Dictionary<string, CustomersDetails> normal_customer { get; set; }
    public Dictionary<string,CustomersDetails> luxury_customer { get; set; }
}

public class RootObject
{
    public Data data { get; set; }
}

Deserialization code:

var result = JsonConvert.DeserializeObject<RootObject>(text);

P.S. I've remove one closing bracket after "ALPHY" element, to make Json valid, I hope it was typo and you're getting valid Json.