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
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