Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with JSON null handling in Newtonsoft

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?

like image 570
Arulkumar Avatar asked Dec 14 '22 13:12

Arulkumar


1 Answers

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);
}
like image 117
dbc Avatar answered Jan 15 '23 12:01

dbc