Is there any way to check if a property or a properties parent exist in Json.NET?
For example: If the json looks like this:
{
'name': 'Sensor1',
'active': true,
'deviceId': 123,
'stats': {
'temp': 10,
'humidity': 50,
'wind': 2
}
It is possible to check if temp exist like this:
var data = JsonConvert.DeserializeObject<dynamic>(json);
double? temp = data["stats"]["temp"]; //returns null if temp does not exist
But if the parent to temp (stats) is missing, an exception occurs and null is not returned.
To summarize: is it possible, given the example, to check if temp or the parent property exists (or simply put if stats.temp exist)?
I realize that I can check stats first and then temp but the json I am dealing with is far more complex than this example.
Update:
I was able to achieve what i wanted using SelectToken("pathToProperty") like this:
JObject obj = JsonConvert.DeserializeObject<dynamic>(json);
JToken jt = obj.SelectToken("stats.temp");
SelectToken returns value if found, otherwise null.