ewomack ewomack - 1 month ago 7x
JSON Question

Newtsonsoft - fInd a property buried in JSON

While parsing a JSON string, I want to test whether a property exists so the app won't throw a "null reference" error in the case the JSON property didn't make it into the string.

The property I'm looking for is buried in the JSON

dateofbirth = (string) o["Person"]["Demographics"]["Birthdate"]["Date"];

And when I try to access the property

var JSONBirthDate = o.Property("Birthdate");

It always returns "null" - I've searched around and can't find the syntax for grabbing a property down in the JSON hierarchy.

Once I can do this, I'm guessing I just check it like this:

if(property != null) {
// do something

And provide a default value.

dbc dbc

You can use SelectToken for this purpose:

var dateofbirth = (string)o.SelectToken("Person.Demographics.Birthdate.Date");

It supports array indexing as well as property selection. E.g., if you had an array of people instead of a single person, you could do:

var dateofbirth = (string)o.SelectToken("People[0].Demographics.Birthdate.Date");

It also supports JSONPath query syntax including the wildcard and recursive descent operator. For the full syntax, see here.