Home > Backend Development > C++ > How can I efficiently search for a specific JToken by name within a nested JObject hierarchy in C# using Newtonsoft.Json?

How can I efficiently search for a specific JToken by name within a nested JObject hierarchy in C# using Newtonsoft.Json?

Mary-Kate Olsen
Release: 2025-01-01 07:38:11
Original
408 people have browsed it

How can I efficiently search for a specific JToken by name within a nested JObject hierarchy in C# using Newtonsoft.Json?

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();
Copy after login

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);
            }
        }
    }
}
Copy after login

This method can be used as follows:

foreach (JToken token in jObject.FindTokens("text"))
{
    Console.WriteLine(token.Path + ": " + token.ToString());
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template