Buda Gavril
Buda Gavril

Reputation: 21637

c#: read value from json using JToken

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?

Upvotes: 1

Views: 2975

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93053

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.

Upvotes: 2

Related Questions