我有一个包含一些数据的JSON对象,我想获取每次出现的特定键名的所有值。是否有任何预定义的方法来搜索JSON对象中所有出现的键或需要编写用户定义的方法?
样本杰森
[{"id":"23","name":"sunny","className":"2","class" :{"className":"1","class2" :{"className":"3","class" :{"className":"4"}}}}]
可以使用LINQ to JSON通过使用SelectTokens具有递归路径的方法来实现..className
SelectTokens
..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'}}}}]"; }
参考文献:
Json.NET-文档-解析JSON
Json.NET 6.0版本1-JSONPath和F#支持
JSONPath表达式