C#不建类直接Json解析与取值

1、添加引用Newtonsoft.Json.dll(附件:https://files.cnblogs.com/files/chen-yuan/Newtonsoft.zip);
2、引用:

using Newtonsoft.Json.Linq;

3、具体代码:

string students = "{\"grade\":\"6\",\"class\":\"1\",\"students\":[{ \"id\":\"1\",\"name\":\"Lily\",\"sex\":\"女?\"},{\"id\":\"2\",\"name\":\"Jack\",\"sex\":\"男D\"},{\"id\":\"3\",\"name\":\"Lucy\",\"sex\":\"女?\"}]}";
JObject studentsJson = JObject.Parse(students);
//年级
string grade = studentsJson["grade"].ToString();
//获得第二个学生的姓名
string name1 = studentsJson["students"][1]["name"].ToString();  //Or
name1 = studentsJson["students"].AsEnumerable().ElementAt(1)["name"].ToString();
//遍历学生信息
var studentsList = studentsJson["students"].AsEnumerable();
foreach (var item in studentsList)
{
    string a = item["name"].ToString();
}
//获得学生Jack的信息和性别
var Jack = studentsJson["students"].AsEnumerable().Where(t => t.Value("name") == "Jack");
string Jack_sex = Jack.FirstOrDefault()["sex"].ToString();
//获得女生的信息集合
var Girls = studentsJson["students"].AsEnumerable().Where(t => t.Value("sex") == "女?");

你可能感兴趣的:(c#,json)