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
复制代码

 

posted @   bingxingc  阅读(323)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示