Reputation: 1176
I have a JObject object which has Json data. I need to collect all KeyValuePairs of whichever has "state": true
. Before I read the value, I want to make sure that the JObject has at least one KeyValuePairs with JToken (Value) has "state": true
.
Below is my 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"
}
}
And the below is the code currently I'm checking with, which is throwing an exception saying 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();
}
Please help me and correct the LinQ statement to read only JTokens with state as true.
Upvotes: 4
Views: 45974
Reputation: 438
This worked for me, looks like you're missing an extra call to Children() to access the properties you need.
//parse JSON and grab it's children.
var jsonData = JObject.Parse(json).Children();
List<JToken> tokens = jsonData .Children().ToList();
or
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();
}
Alternatively you could do this. The code below will return a dictionary with only your states with true values. Otherwise, it will return an empty dictionary if you have no true values.
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
}
Upvotes: 9