Net Core教程

C# Json和对象的转换,序列化和反序列化

本文主要是介绍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

 

这篇关于C# Json和对象的转换,序列化和反序列化的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!