Home >Backend Development >C++ >How to Efficiently Retrieve Specific JTokens by Name from a JObject Hierarchy?
Traversing JObject Hierarchy for Specific Token by Name
Problem:
Given a JSON response with a complex hierarchy of JTokens, how can you retrieve a specific JToken by its name efficiently?
Newtonsoft.Json Built-In Function:
Newtonsoft.Json provides the SelectToken() method, which allows direct navigation to a token based on its path. For example:
JToken distance = jObject.SelectToken("routes[0].legs[0].distance.text");
This retrieves the JToken representing the distance text value.
Recursive Search:
If the token's path is not known or you need to find all occurrences of a token with a given name, a recursive search is necessary. Here's a custom helper method for recursive searching:
public static class JsonExtensions { public static List<JToken> FindTokens(this JToken containerToken, string name) { List<JToken> matches = new List<JToken>(); FindTokens(containerToken, name, matches); return matches; } private static void FindTokens(JToken containerToken, string name, List<JToken> matches) { if (containerToken.Type == JTokenType.Object) { foreach (JProperty child in containerToken.Children<JProperty>()) { if (child.Name == name) { matches.Add(child.Value); } FindTokens(child.Value, name, matches); } } else if (containerToken.Type == JTokenType.Array) { foreach (JToken child in containerToken.Children()) { FindTokens(child, name, matches); } } } }
Usage:
string json = @"...", jo = JObject.Parse(json); foreach (JToken token in jo.FindTokens("text")) { Console.WriteLine(token.Path + ": " + token.ToString()); }
Output:
routes[0].legs[0].distance.text: 1.7 km routes[0].legs[0].duration.text: 4 mins routes[0].legs[1].distance.text: 2.3 km routes[0].legs[1].duration.text: 5 mins
The above is the detailed content of How to Efficiently Retrieve Specific JTokens by Name from a JObject Hierarchy?. For more information, please follow other related articles on the PHP Chinese website!