Nanji Mange Nanji Mange - 21 days ago 5
ASP.NET (C#) Question

How to deserialize JSON data in asp.net?

I have following JSON data, class and code but it doesn't working. I am getting List of 3 object but all are NULL. Can anybody please suggest me what I am missing here?

JSON data:

[
{
"donotpostalmail": {
"Do Not Allow": {
"Do Not Allow": 1
},
"Allow": {
"Allow": 0
}
}
},
{
"familystatuscode": {
"Single": {
"Single": 1
},
"Married": {
"Married": 2
},
"Divorced": {
"Divorced": 3
},
"Widowed": {
"Widowed": 4
}
}
},
{
"preferredcontactmethodcode": {
"Any": {
"Any": 1
},
"Email": {
"Email": 2
},
"Phone": {
"Phone": 3
},
"Fax": {
"Fax": 4
},
"Mail": {
"Mail": 5
}
}
}
]


Class:

public class ResponseDataOfOptions
{
public OptionsList mainList { get; set; }
}
public class OptionsList
{
public Dictionary<string, Options> optionList { get; set; }
}
public class Options
{
public Dictionary<string, int> options { get; set; }
}


.cs file Code:

List<ResponseDataOfOptions> optionList = JsonConvert.DeserializeObject<List<ResponseDataOfOptions>>(objResponse.ResponseDataOfOptions);

Answer

You cannot use objects in this case because every object has different property names. The only way to deserialize this JSON is as follows.

 JsonConvert.DeserializeObject<List<Dictionary<string, 
      Dictionary<string, 
          Dictionary<string, int>
      >
 >>(objResponse.ResponseDataOfOptions);

It is a list of dictionaries, in fact there are three levels of dictionaries. It's not a very friendly structure to work with data but that would do the deserialize.

You might also be interested in using some property detection using JObject and JToken and then inflate appropriate data transfer objects.

JObject list = JObject.Parse(objResponse.ResponseDataOfOptions);
foreach (var item in list) {
    JToken token = jobj["donotpostalmail"];
    if (token != null) {
        // inflate the corresponding data type.
    }
}