Newtonsoft中的JSON空处理问题 [英] Issue with JSON null handling in Newtonsoft

查看:159
本文介绍了Newtonsoft中的JSON空处理问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理Newtonsoft.json时,我在处理null时遇到问题.

I have an issue with null handling when dealing Newtonsoft.json.

我要检查结果是否为null.基于此,我想处理一些情况.

I want to check the result is null or not. Based on that I want to handle some condition.

我的代码如下:

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);
    }
}

带有nulljsonContent如下:

{
     "User": null
}

如果"User": nulljsonContent["User"]返回{},并且jsonContent["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.

因此,对于null处理,我使用了以下代码:

So for null handling, I used this code:

if (jsonContent["User"].Value<string>() != null)

如果"User": null,则上面的代码可以正常工作.

If the "User": null, the above code works fine.

但是,如果jsonContent["User"]具有有效数据,则会引发错误.

But if jsonContent["User"] have valid data, it throws an error.

无法将Newtonsoft.Json.Linq.JObject转换为Newtonsoft.Json.Linq.JToken

Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken

具有有效数据的jsonContent如下:

{
    "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"
    }
}   

如何使用有效数据和null值实现此null处理?

How can I achieve this null handling for with valid data and null value?

推荐答案

您可以检查 JTokenType.Null :

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;
    }
}

然后执行:

if (!user.IsNull())
{
    membershipUser = GetMembershipUser(user);
}

这篇关于Newtonsoft中的JSON空处理问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆