Cannot Access Child Value on Newtonsoft. Json. Linq. Jproperty -Error Happens While Checking Jobject Using Linq

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.

0

1 Answer

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest