Reputation: 13237
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?
Upvotes: 4
Views: 9777
Reputation: 2210
I add to expand on dbc's answer above, since I found a situation where a JToken is assigned to null by a string variable. The JTokenType is then JTokneType.String, but the value is still null.
using Newtonsoft.Json.Linq;
namespace Common
{
public static class JTokenExtensions
{
public static bool IsNull(this JToken token)
{
if (token == null || token.Type == JTokenType.Null)
{
return true;
}
// Catch the case where a user uses a NULL string variable to set the JToken to null
// If it was directly assigned to a null, the test above will work; however, if you
// set the JToken with a string variable that is null, you need this test!
if (token.Type == JTokenType.String)
{
string result = token.Value<string>();
if (result == null)
{
return true;
}
}
return false;
}
}
}
Upvotes: 3
Reputation: 116721
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);
}
Upvotes: 14