The issue I’m having is how to Deserialize the following JSON. The values of Answer is sometimes NULL, true, an integer, boolean, or contain another list of JSON (id, description and so on).
The first step I did was to copy and paste special as class in Visual Studio. This provided me with the following Questions class.
I then tried to deserialize this (following C# - where rawResponse is the JSON). However, I get the “Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type Applicated.Questions because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly....“
I understand it’s something to do with it not mapping correctly.
Therefore, tried to put this all in a foreach loop by saving the response in a dynamic variable (note I did remove the Property1 from Questions class for this). However, some results within Answer store the string Id, Description and so on in the Answer field. Is there an easier way of doing this, I seem to have reached a mental block?
JSON:
[
{
"Answer": true,
"QuestionId": 55,
"Title": "Are you Married?",
"AnswerType": "Boolean"
},
{
"Answer": {
"Id": "1",
"Description": "Female",
"Reference": "F",
"ArchiveDate": null,
"ParentId": null,
"OptionType": {
"Id": 40,
"Type": "dropdown"
}
},
"QuestionId": 778,
"Title": "Gender",
"AnswerType": "Option”
}
]
CLASS:
public class Questions
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public object Answer { get; set; }
public int QuestionId { get; set; }
public string Title { get; set; }
public string AnswerType { get; set; }
}
C#:
Questions result = JsonConvert.DeserializeObject<Questions>(rawResponse);
C# Dynamic Foreach
dynamic result = JsonConvert.DeserializeObject(rawResponse);
var lstQuestionObjects = new List<Questions>();
foreach(var obj in result)
{
lstQuestionObjects.Add(new Questions()
{
Answer = (obj.Answer !=null) ? obj.Answer.ToString() :"",
QuestionId = int.Parse(obj.QuestionId.ToString()),
Title = (obj.Title != null) ? obj.Title.ToString() : "",
AnswerType = (obj.AnswerType != null) ? obj.AnswerType.ToString() : ""
});
}