C# Newtonsoft.Json之LINQ To Json实例(二)

时间:2022-04-15 05:15:59

Querying JSON with LINQ 解析获取json 字符串中的内容 ,对于单级的可以,对于多级的时候建议使用下一种方式
//Querying with LINQ  
string json = @"{  
    school:{  
    name:'实验高中',  
    students:[  
        {name:'张三',age:18},  
        {name:'李四',age:19}  
    ],  
    sites:['济南','聊城']  
    }  
}";  
JObject o = JObject.Parse(json);  
string schname = (string)o["school"]["name"];  
Console.WriteLine(schname); //实验高中  
string stuname = (string)o["school"]["students"][1]["name"];  
Console.WriteLine(stuname);//李四  
JArray sites = (JArray)o["school"]["sites"];  
foreach (var item in sites)  
{  
    Console.WriteLine(item); //济南  //聊城  
}  
IList<string> siteList = sites.Select(q => (string)q).ToList();  
Console.WriteLine(sites.Count);//2  

Querying JSON width SelectToken 使用SelectToken 方式获取json 字符串中的内容 (比较推荐的方式)
//  Querying JSON with SelectToken  
string json = @"{  
    school:{  
    name:'实验高中',  
    students:[  
        {name:'张三',age:18},  
        {name:'李四',age:19}  
    ],  
    sites:['济南','聊城']  
    }  
}";  
JObject o = JObject.Parse(json);  
//SelectToken 方法使用  
string schname = (string)o.SelectToken("school.name");  
Console.WriteLine(schname); //实验高中  
string stuname = (string)o.SelectToken("school.students[1].name");  
Console.WriteLine(stuname); //李四  
//SelectToken with JSONPath  
JToken stu1 = o.SelectToken("$.school.students[?(@.name=='张三')]");  
Console.WriteLine(stu1); //{"name": "张三","age": 18}  
Console.WriteLine(stu1["age"]); //18  
IEnumerable<JToken> stus = o.SelectTokens("$..students[?(@.age>15)]");  
foreach (var item in stus)  
{  
    Console.WriteLine(item); //{"name": "张三",   "age": 18 }    
                                //{ "name": "李四",   "age": 19}  
}  
//SelectToken with LINQ  
// $...name  意思是从当前接口文档的1,2,3级中查找name,并返回结果  
IList<string> names = o.SelectTokens("$...name").Select(q => (string)q).ToList();  
Console.WriteLine(string.Join(",",names)); //实验高中,张三,李四