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

查看:679
本文介绍了检查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 此...

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

我尝试了((JObject)obj)。计数也可以。但是似乎没有用。

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天全站免登陆