Searching for a Specific JToken by Name in a JObject Hierarchy
When working with JSON data in C#, the Newtonsoft.Json library provides various methods to interact with JObjects and JTokens. If you need to retrieve a specific JToken by name from a JObject hierarchy, you may be wondering if there is a built-in function that can simplify this task.
Using SelectToken() for Specific Token Navigation
If you know the exact path to the JToken you want to retrieve, the SelectToken() method provides a direct way to navigate to it. For instance:
JObject jObject = ...; string distanceText = jObject.SelectToken("routes[0].legs[0].distance.text").ToString();
In this example, we retrieve the "text" JToken from the distance property nested within the first leg of the first route.
Implementing a Recursive Search for All Tokens
If you need to find all occurrences of a JToken with a given name regardless of its location within the JObject hierarchy, you will need to implement a recursive search method. Here's one approach:
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); } } } }
This method can be used as follows:
foreach (JToken token in jObject.FindTokens("text")) { Console.WriteLine(token.Path + ": " + token.ToString()); }
The resulting output will display the path and value of all JTokens with the name "text". For example:
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 can I efficiently search for a specific JToken by name within a nested JObject hierarchy in C# using Newtonsoft.Json?. For more information, please follow other related articles on the PHP Chinese website!