C#json字符串序列化和反序列化
时间: 2023-11-21 13:55:27 浏览: 209
一个c#的json序列化和反序列化类
3星 · 编辑精心推荐
以下是C#中进行Json字符串序列化和反序列化的示例代码:
1. 序列化实体类对象为Json字符串
```csharp
using Newtonsoft.Json;
// 定义实体类
public class Student
{
public int studentID { get; set; }
public string studentName { get; set; }
public int studentAge { get; set; }
public string studentSex { get; set; }
}
// 创建实体类对象
Student studentOne = new Student();
studentOne.studentID = 1;
studentOne.studentName = "张三";
studentOne.studentAge = 18;
studentOne.studentSex = "男";
// 序列化为Json字符串
string json = JsonConvert.SerializeObject(studentOne);
Console.WriteLine(json); // 输出:{"studentID":1,"studentName":"张三","studentAge":18,"studentSex":"男"}
```
2. 反序列化Json字符串为实体类对象
```csharp
using Newtonsoft.Json;
// 定义实体类
public class Student
{
public int studentID { get; set; }
public string studentName { get; set; }
public int studentAge { get; set; }
public string studentSex { get; set; }
}
// 反序列化为Student实体类对象
string json = "{\"studentID\":1,\"studentName\":\"张三\",\"studentAge\":18,\"studentSex\":\"男\"}";
Student studentTwo = JsonConvert.DeserializeObject<Student>(json);
Console.WriteLine(studentTwo.studentName); // 输出:张三
```
阅读全文