0

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.

karra
  • 176
  • 4
  • 15
  • `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.` Please update your example to be of equivalent complexity. – mjwills Feb 20 '18 at 20:37
  • mjwills: The example is representative, what i meant by more complex is that it contains hundreds of properties (on different levels) and it would be tedious work to check if every level exist. I would like to check if property1.property2.property3 exist instead of checking them all independently. – karra Feb 20 '18 at 20:42
  • Not sure if this will work in your case but have you looked at [TryGetValue](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_TryGetValue.htm) – Rick S Feb 20 '18 at 20:44
  • It seem like it'd be trivial to write a function that takes a dynamic object and an array of property names (or even a string and then split by a delimiter, such as `"prop1.prop2.prop3"`), then walk down the array until either you hit a null or get to the end of the array and return a value. You could even make it generic so that it handles casting for you. – JDB Feb 20 '18 at 20:49
  • Would a `try..catch` be useful? `public static object GetValue(Func getValue) { try { return getValue(); } catch (Exception e) { return null; } } ` – mjwills Feb 20 '18 at 20:51
  • Thank you for the suggestions! I think i might be able to achieve what i want using SelectToken("stats.temp"). It will return the value if it exists, otherwise null. – karra Feb 20 '18 at 21:05
  • Related or duplicate: [Json.NET get nested jToken value](https://stackoverflow.com/q/42290485). – dbc Feb 20 '18 at 23:21

0 Answers0