I have an issue with null
handling when dealing Newtonsoft.json
.
I want to check the result is null
or not. Based on that I want to handle some condition.
My code is as below:
try {
var response = GetApiData.Post(_getApiBaseUrl, data.ToString());
var jsonString = response.ResultString;
var jsonContent = JObject.Parse(jsonString);
if (jsonContent["User"] != null) // <-- null handling
{
var user = JToken.Parse(jsonContent["User"].ToString());
membershipUser = GetMembershipUser(user);
}
}
The jsonContent
with null
is as below:
{
"User": null
}
If the "User": null
the jsonContent["User"]
returns {}
and jsonContent["User"] != null
condition did not throw any error, but instead of skip the block, it executes the inner lines.
So for null
handling, I used this code:
if (jsonContent["User"].Value<string>() != null)
If the "User": null
, the above code works fine.
But if jsonContent["User"]
have valid data, it throws an error.
Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken
The jsonContent
with valid data is as below:
{
"User": {
"Claims": [],
"Logins": [],
"Roles": [],
"FirstName": "Unknown",
"LastName": "Unknown",
"IsApproved": true,
"IsDeleted": false,
"Email": "testuser@user.com",
"EmailConfirmed": false,
"PasswordHash": "AC/qXxxxxxxxxx==",
"SecurityStamp": "001f3500-0000-0000-0000-00f92b524700",
"PhoneNumber": null,
"PhoneNumberConfirmed": false,
"TwoFactorEnabled": false,
"LockoutEndDateUtc": null,
"LockoutEnabled": false,
"AccessFailedCount": 0,
"Id": "00f50a00-0000-0000-0000-000b97bf2800",
"UserName": "testUser"
}
}
How can I achieve this null handling for with valid data and null value?