1

Is there a way to navigate a JSON safely?

Given this JSON,

{
  "foo": { 
    "bar": { 
      "baz": "quz"
    }
  }   
}

I'd like to navigate it safely similar to the line below without creating types for all of them.

string value1 = jObj.foo?.bar?.baz ?? "default";
// value1 == "quz"

string value2 = jObj.foo?.abc?.def ?? "default";
// value2 == "default"

I might be able to write an extension method with this signature but please let me know if there is an easier way for the safe navigation.

string value = jObj.Value(
  "foo.bar?.baz?[1].qux",
  "default"
);
Poulad
  • 1,149
  • 1
  • 12
  • 22
  • Why not just use the null conditional index operator e.g. as shown in [Json.NET get nested jToken value](https://stackoverflow.com/a/42300875/3744182). – dbc Oct 08 '18 at 21:34

1 Answers1

1

For the exact syntax you mention, you can cast your JObject as dynamic.

var jObj = JsonConvert.DeserializeObject<dynamic>(text);
string value1 = jObj.foo?.bar?.baz ?? "default";

Here's a LINQPad sample showing your example working as expected.

If you'd prefer to avoid dynamic (I wouldn't blame you), you can use SelectToken like this:

var jObj = JsonConvert.DeserializeObject<JObject>(text);
string value1 = (string)jObj.SelectToken("foo.bar.baz") ?? "default";

http://share.linqpad.net/h4bnui.linq

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315