简体   繁体   中英

Find a value of all occurrences from the json string in c#

I have a JSON object with some data and I want to get all the values of each occurrence of specific key name. Is there any predefined method to search for a key in JSON object for all occurrences or need to write user defined method?

Sample Json

[{"id":"23","name":"sunny","className":"2","class" :{"className":"1","class2" :{"className":"3","class" :{"className":"4"}}}}]

This can be achieved with LINQ to JSON by using the SelectTokens method with a recursive path ..className

class Program
{
    static void Main(string[] args)
    {
        JObject jObject = JObject.Parse(jsonString);

        // You would use this because you have an array.
        // JArray jObject = JArray.Parse(jsonArray);

        // .. - recursive descent
        var classNameTokens = jObject.SelectTokens("..className"); 
        var values = classNameTokens.Select(x => (x as JValue).Value);
    }

    static string jsonString = @"{'id':'23','name':'sunny','className':'2','class' :{'className':'1','class2' :{'className':'3','class' :{'className':'4'}}}}";
    static string jsonArray = @"[{'id':'23','name':'sunny','className':'2','class' :{'className':'1','class2' :{'className':'3','class' :{'className':'4'}}}}]";
}

References:

Json.NET - Documentation - Parsing JSON

Json.NET 6.0 Release 1 - JSONPath and F# Support

JSONPath expressions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM