从c#中的json字符串中查找所有出现的值

时间:2014-11-26 04:36:24

标签: c# json search

我有一个带有一些数据的JSON对象,我希望得到每次出现的特定键名的所有值。是否有任何预定义方法在JSON对象中搜索所有出现的键或需要编写用户定义的方法?

示例Json

[{"id":"23","name":"sunny","className":"2","class" :{"className":"1","class2" :{"className":"3","class" :{"className":"4"}}}}]

1 个答案:

答案 0 :(得分:6)

使用SelectTokens方法和递归路径..className

,可以使用LINQ to JSON实现这一点
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

Json.NET 6.0 Release 1 - JSONPath and F# Support

JSONPath expressions