我有一个包含 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 语句以仅读取 state 为 true 的 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();
}
或者你可以这样做。下面的代码将返回一个字典,其中只有您的状态具有真实值。否则,如果您没有真值,它将返回一个空字典。
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/