c# - 无法访问 Newtonsoft.Json.Linq.JProperty 上的子值 - 使用 LinQ 检查 JObject 时发生错误

标签 c# linq json.net

我有一个包含 Json 数据的 JObject 对象。我需要收集具有 "state": true 的所有 KeyValuePairs。在我读取值之前,我想确保 JObject 至少有一个 KeyValuePairs 和 JToken (Value) 有 "state": true
下面是我的 JSON:

{  
  "AAA": {
    "state": false,
    "version": "1.1.14202.0",
    "result": null,
    "update": "20171018"
  },
  "BBB": {
    "state": true,
    "version": "3.10.1.18987",
    "result": null,
    "update": "20171018"
  },
  "CCC": {
    "state": true,
    "version": "1.1.1.2",
    "result": null,
    "update": "20171018"
  }
}

下面是我正在检查的代码,它抛出一个异常,提示 Cannot access child value on Newtonsoft.Json.Linq.JProperty:

JObject jsonData = //JSON data;
List<JToken> tokens = jsonData .Children().ToList();
if (tokens.Any(each => each["state"].ToString().ToLower().Contains("true")))
{
  List<JToken> tokensWithStateTrue = tokens.Where(each => each["state"].ToString().ToLower().Contains("true")).ToList();
}

请帮助我并更正 LinQ 语句以仅读取 statetrue 的 JTokens。

最佳答案

这对我有用,看起来您缺少对 Children() 的额外调用以访问您需要的属性。

//parse JSON and grab it's children. 
var jsonData = JObject.Parse(json).Children();

List<JToken> tokens = jsonData .Children().ToList(); 

List<JToken> tokens = jsonData .Children().Children().ToList();
if (tokens.Any(each => each["state"].ToString().ToLower().Contains("true")))
{
    List<JToken> tokensWithStateTrue = tokens.Where(each => each["state"].ToString().ToLower().Contains("true")).ToList();
}

enter image description here

或者你可以这样做。下面的代码将返回一个字典,其中只有您的状态具有真实值。否则,如果您没有真值,它将返回一个空字典。

var dictionaryTokensWithTrueValues = jsonData.Children()
.Select(u => u as JProperty)
.Where(v => v.Value["state"].ToString().ToLower().Contains("true"))
.ToDictionary(k => k.Name, v => v.Value);

//check if you have any true values
if (dictionaryTokensWithTrueValues.Count() > 0)
{
     //do something with true states here
     var accessBBB = dictionaryTokensWithTrueValues["BBB"]; //{{"state": true,"version": "3.10.1.18987","result": null,"update": "20171018"}}
}
else
{ 
     //no true states. Do something else
}

关于c# - 无法访问 Newtonsoft.Json.Linq.JProperty 上的子值 - 使用 LinQ 检查 JObject 时发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49254281/

相关文章:

c# - 从 C# 调用 C++ DLL 的类成员

c# - 替换系统对象的策略

c# - Linq 优化的相交查询

c# - 将 IEnumerable<T> 转换为 JSON 对象

c# - xunit 多次测试事实

c# - 将值从字符串转换为 Guid 或 int 的泛型类型

c# - 在创建表单实例时应用 CulutureInfo

c# - LINQ 如何根据给定条件对项目进行排序?

c# - 传递 JSON,反序列化因反斜杠而失败

c# - Newtonsoft.Json - 从 JSON 中获取反序列化对象的相应行号,以便更好地处理错误