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

后端 未结 1 1728
清酒与你
清酒与你 2020-12-19 23:56

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 obje

相关标签:
1条回答
  • 2020-12-20 00:01

    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

    0 讨论(0)
提交回复
热议问题