C# Json和对象的转换,序列化和反序列化
序列化:
Student student1 = new Student { Id = 12883, Name = "Jim David", Scores = new double[] { 87.5, 92, 76.2 } }; Student student2 = new Student { Id = 35228, Name = "Milly Smith", Scores = new double[] { 92.5, 88, 85.7 } }; List<Student> students = new List<Student>(); students.Add(student1); students.Add(student2); string jsonStudents = JsonConvert.SerializeObject(students, Formatting.Indented); //[ // { // "Id": 12883, // "Name": "Jim David", // "Scores": [ // 87.5, // 92.0, // 76.2 // ] // }, // { // "Id": 35228, // "Name": "Milly Smith", // "Scores": [ // 92.5, // 88.0, // 85.7 // ] // } //]
反序列化:
string jsonStudentList = @"[ { 'Id': 12883, 'Name': 'Jim David', 'Scores': [ 87.5, 92.0, 76.2 ] }, { 'Id': 35228, 'Name': 'Milly Smith', 'Scores': [ 92.5, 88.0, 85.7 ] } ]"; List<Student> studentsList = JsonConvert.DeserializeObject<List<Student>>(jsonStudentList); Console.WriteLine(studentsList.Count); //2 Student s = studentsList[0]; Console.WriteLine(s.Name); //Jim David