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": "[email protected]",
        "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?
You can check for JToken.Type being JTokenType.Null:
var jsonContent = JObject.Parse(jsonString);
var user = jsonContent["User"];
if (user != null && user.Type != JTokenType.Null)
{
    membershipUser = GetMembershipUser(user);
}
To make the check more convenient, an extension method could be introduced:
public static partial class JTokenExtensions
{
    public static bool IsNull(this JToken token)
    {
        return token == null || token.Type == JTokenType.Null;
    }
}
And then do:
if (!user.IsNull())
{
    membershipUser = GetMembershipUser(user);
}
                        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