I have a JSON structure like below to show the details of a specific candidate It can be either null or can contain some details like below
"details": {
"gender": {
"id": 3,
"props": {
"name": "male"
}
}
}
or as null
"details": {
"gender": null
}
To read the value of gender i tried
string _gender = (string)result["details"]["gender"]["props"]["name"];
This will works in non null cases . But if its null then this code returns an exception
So to check first is it null or not and if not null try to read the value, i tried below code
string _gender = (string)result["details"]["gender"];
if (!string.IsNullOrEmpty(_gender))
{
_gender = (string)result["details"]["gender"]["props"]["name"];
}
But i am getting the exception that not possible to convert object to string. So how to read a JSON property with proper null handling \
detailsnullable and deserialize your json to an object e.g.List<YourObject>. Then fetch the details property for all instances.if(result["details"]["gender"] != null)? Remember thatresult["details"]["gender"]is of type JToken, not string