I am calling a webservice which returns the response in json in the following format.
{
"parent":
{
"child": {
"key1": value1,
"key2": value2
}
}
}
The above reponse is when there is only one child in the parent. But when there are more than one child in parent, then the response is as shown:
{
"parent": [
{
"child": {
"key1": "value1",
"key2": "value2"
}
},
{
"child": {
"key1": "value1",
"key2": "value2"
}
}
]
}
Thus when there are more than one child elements, the parent is a JArray and when there is only child element, the parent is JObject.
Now I am having difficulty in parsing the contents of the child elements dynamically as it throws error of index when it is JObject.
Can someone explain how we can parse the contents both during JObject and JArray.
Currently I am checking the parent tag as whether it is JObject/ JArray and correspondingly parsing, but it is a long and tedious process.
Is there any other method for the same.
Following is code that I am using now
if(jsonfile["parent"].getType() == "JObject")
{
string value1 = (string)jsonfile["parent"]["child"]["key1"]
}
else
{
string value1 = (string)jsonfile["parent"][0]["child"]["key1"];
}
Is there any other method where we can get value1 without checking whether parent is JObject or JArray?