Checking for empty or null JToken in a JObject(检查 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).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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查 JObject 中的空或空 JToken
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
