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 \
I strongly suggest you to deserialize the json as known type.
public class Props
{
public string name { get; set; }
}
public class Gender
{
public int id { get; set; }
public Props props { get; set; }
}
public class Details
{
public Gender gender { get; set; }
}
public class JsonObject
{
public Details details { get; set; }
}
Then perform deserialization;
var jsonObject = JsonConvert.DeserializeObject<List<JsonObject>>(json);
foreach (var o in jsonObject)
{
var genderName = o?.details?.gender?.props?.name;
}
In this way, you can handle the possible null values and get strongly typed object.
EDIT
Also, in your code, you are trying to convert an object to string and it is completely wrong. It seems that gender object is a complex type. So you can't convert it to string and you should modify your code like this;
object _gender = result["details"]["gender"];
if (_gender != null)
{
string genderName = result["details"]["gender"]["props"]["name"].ToString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With