1

I have a json and I want to get a value from a complex object. Here is my json:

{
    "a1" : {
        "a2" : {
            "a3" : "desired_value"
        }
    }
}

And I want to obtain the value "desired value". I've tried to obtain it with this code:

    var token = JToken.Parse(json);
    string value = token.Value<string>("a1.a2.a3");

But the value string is null. What should I put in the path so I can read this only once, I mean without getting a token and then iterate trough it's childern and so?

Buda Gavril
  • 21,409
  • 40
  • 127
  • 196
  • Did you try using JObject ? This link might help you. https://stackoverflow.com/questions/16795045/accessing-all-items-in-the-jtoken-json-net – Demeter Dimitri Jul 18 '18 at 07:30

1 Answers1

2

You can use SelectToken in order to select the property using its path and then extract the value from that:

string value = token.SelectToken("a1.a2.a3").Value<string>();

SelectToken will return null if the path isn't found, so you might want to guard against that.

JToken.Value expects a key to be provided, whereas SelectToken supports both keys and paths (a key is a simple path). You are providing a path where a key is expected, which results in a value not being found.

To demonstrate the difference, you could also retrieve the value of a3 like this:

token.SelectToken("a1.a2").Value<string>("a3");

I wouldn't recommend doing it this way, but it does show how paths involve traversal but keys are simple indexers.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203