C#Json字符串序列化和反序列化实体类对象

2021年9月6日 31点热度 0条评论 来源: 够钟123

1.引入命名空间

using Newtonsoft.Json;

2.定义实体类

public class Student
{
    public int studentID { get; set; }

    public string studentName { get; set; }

    public int studentAge { get; set; }

    public string studentSex { get; set; }
}

3.序列化和反序列化实体类对象

Student studentOne = new Student();
studentOne.studentID = 1;
studentOne.studentName = "张三";
studentOne.studentAge = 18;
studentOne.studentSex = "男";

//序列化为Json字符串
string json = JsonConvert.SerializeObject(studentOne);

//反序列化为Student实体类对象
Student studentTwo = JsonConvert.DeserializeObject<Student>(json);

4.序列化和反序列化实体类对象集合

List<Student> studentListOne = new List<Student>()
{
    new Student{ studentID = 1, studentName = "张三", studentAge = 18, studentSex = "男" },
    new Student{ studentID = 2, studentName = "李四", studentAge = 18, studentSex = "女" },
    new Student{ studentID = 3, studentName = "王五", studentAge = 18, studentSex = "女" }
};

//序列化为Json字符串
string json = JsonConvert.SerializeObject(studentListOne);

//反序列化为Student实体类对象集合
List<Student> studentListTwo = JsonConvert.DeserializeObject<List<Student>>(json);

    原文作者:够钟123
    原文地址: https://blog.csdn.net/qq_42756590/article/details/118936067
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。