Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
CSS
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?

Any help would be greatly appreciable.

this is sample json object and I want to get all the values with key 'className' [{"id":"23","name":"sunny","className":"2","class" :{"className":"1","class2" :{"className":"3","class3" :{"className":"4"}}}}]
Posted

You can deserialize json data to a strongly type by using newtonsoft.After that you can filter by using Linq
http://stackoverflow.com/questions/5979434/deserializing-json-array-into-strongly-typed-net-object[^]
Hope this helps
 
Share this answer
 
XML
This can be achieved with LINQ to JSON by using the SelectTokens method with a recursive path ..className


<pre lang="cs">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(&quot;..className&quot;);
        var values = classNameTokens.Select(x =&gt; (x as JValue).Value);
    }

    static string jsonString = @&quot;{&#39;id&#39;:&#39;23&#39;,&#39;name&#39;:&#39;sunny&#39;,&#39;className&#39;:&#39;2&#39;,&#39;class&#39; :{&#39;className&#39;:&#39;1&#39;,&#39;class2&#39; :{&#39;className&#39;:&#39;3&#39;,&#39;class&#39; :{&#39;className&#39;:&#39;4&#39;}}}}&quot;;
    static string jsonArray = @&quot;[{&#39;id&#39;:&#39;23&#39;,&#39;name&#39;:&#39;sunny&#39;,&#39;className&#39;:&#39;2&#39;,&#39;class&#39; :{&#39;className&#39;:&#39;1&#39;,&#39;class2&#39; :{&#39;className&#39;:&#39;3&#39;,&#39;class&#39; :{&#39;className&#39;:&#39;4&#39;}}}}]&quot;;
}</pre>



http://stackoverflow.com/questions/27141419/find-a-value-of-all-occurrences-from-the-json-string-in-c-sharp[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900