检查JObject中的空/空JToken [英] Checking for empty/null JToken in a JObject

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

问题描述

我有以下...

JArray clients = (JArray)clientsParsed["objects"];

foreach (JObject item in clients.Children())
{
    // etc.. SQL params stuff...
    command.Parameters["@MyParameter"].Value = JTokenToSql(item["thisParameter"]);
}

JTokenToSql看起来像这样...

JTokenToSql looks like this...

public static object JTokenToSql(JToken obj)
{
    if (obj.Any())
        return (object)obj;
    else
        return (object)DBNull.Value;
}

我也尝试过((JObject)obj).Count.但是似乎没有用.

I have tried ((JObject)obj).Count also.. But doesn't seem to be working.

推荐答案

要检查JObject上是否存在属性,可以使用方括号语法并查看结果是否为null.如果该属性存在,则将始终返回JToken(即使JSON中的值为null).

To check whether a property exists on a JObject, you can use the square bracket syntax and see whether the result is null or not. If the property exists, a JToken will be always be returned (even if it has the value null in the JSON).

JToken token = jObject["param"];
if (token != null)
{
    // the "param" property exists
}

如果手边有一个JToken,并且想查看它是否为非空,那么这取决于它是什么类型的JToken以及如何定义空".我通常使用这样的扩展方法:

If you have a JToken in hand and you want to see if it is non-empty, well, that depends on what type of JToken it is and how you define "empty". I usually use an extension method like this:

public static class JsonExtensions
{
    public static bool IsNullOrEmpty(this JToken token)
    {
        return (token == null) ||
               (token.Type == JTokenType.Array && !token.HasValues) ||
               (token.Type == JTokenType.Object && !token.HasValues) ||
               (token.Type == JTokenType.String && token.ToString() == String.Empty) ||
               (token.Type == JTokenType.Null);
    }
}

这篇关于检查JObject中的空/空JToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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