Parse Json using LitJson

You can install LitJson packages through NuGet

or

Add a reference directly

LitJSON. DLL download

Link: pan.baidu.com/s/1IsGPE4FF… Extraction code: UN7P

Create a studentsinfo. json file for the test

[{" ID ": 1001," Name ":" ha ha ", "Class" : "1"}, {" ID ": 1002," Name ":"... ", "Class" : "2"}, {" ID ": 1003," Name ": ", "Class": "1"}]Copy the code

Create a Model

public class Student { public int ID { get; set; } public string Name { get; set; } public string Class { get; set; } public override string ToString() { return string.Format("ID:{0},Name:{1},Class:{2}", ID, Name, Class); }}Copy the code

Read parse Josn

JsonData data = jsonmapper.toobject (file.readallText (" studentsinfo.json ")); List<Student> stuList = new List<Student>(); foreach (JsonData item in data) { Student stu = new Student(); stu.ID = int.Parse(item["id"].ToString()); stu.Name = item["name"].ToString(); stu.Class = item["class"].ToString(); stuList.Add(stu); } foreach (var stu in stuList) {console.writeline (stu.tostring ()); }Copy the code

Using generics to get Josn data is more convenient

Note that the Json data name is the same as the Model property name

List < Student > stuList = JsonMapper.ToObject<List<Student>>(File.ReadAllText("StudentsInfo.json")); Foreach (var stu in stuList) {console.writeline (stu.tostring ()); }Copy the code

The output

The Josn data above is an array. What if it is an object, i.e. a student’s information

Json file

{" ID ": 1001," Name ":" ha ha ", "Class" : "1", "CourseList" : [{" ID ": 501," Name ":" the language "}, {" ID ": 502," Name ":" mathematics "}]}Copy the code

Create a Model

public class Student { public int ID { get; set; } public string Name { get; set; } public string Class { get; set; } public List<Course> CourseList { get; set; } public override string ToString() { return string.Format("ID:{0},Name:{1},Class:{2}", ID, Name, Class); } } public class Course { public int ID { get; set; } public string Name { get; set; } public override string ToString() { return string.Format("ID:{0},Name:{1}", ID, Name); }}Copy the code

Parsing Json

Student stu = jsonmapper.toobject <Student>(file.readallText (" studentsinfo.json ")); / / output to the Console. WriteLine (stu. ToString ()); foreach (var course in stu.CourseList) { Console.WriteLine(course.ToString()); }Copy the code

The output

Object turn Josn

Student stu = new Student() {ID = 110,Name =" ha ha ",Class =" 101"}; string json = JsonMapper.ToJson(stu); Console.WriteLine(json);Copy the code

The output

The Name value is converted to Unicode encoding

Related links:

Json verification formatting tool: www.bejson.com/

Josn editor: www.bejson.com/jsoneditoro…