我有一个带有一些数据的JSON对象,我希望得到每次出现的特定键名的所有值。是否有任何预定义方法在JSON对象中搜索所有出现的键或需要编写用户定义的方法?
示例Json
[{"id":"23","name":"sunny","className":"2","class" :{"className":"1","class2" :{"className":"3","class" :{"className":"4"}}}}]
答案 0 :(得分:6)
使用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 - Documentation - Parsing JSON