System.Text.Json
程序里的对象(比如一个 Person 类)是机器能懂的,但网络传输或保存到文件时,需要变成纯文本。
JSON 就是一种通用的文本格式,像下面这样:
JSON
{ "name": "小明", "age": 20 }
序列化 = 把 C# 对象翻译成 JSON 字符串
反序列化 = 把 JSON 字符串翻译回 C# 对象
案例 1:把对象变成 JSON 字符串(序列化)
csharp
using System.Text.Json;
var person = new { Name = "小明", Age = 20 };
string json = JsonSerializer.Serialize(person);
Console.WriteLine(json);
// 输出:{"Name":"小明","Age":20}
Serialize 就是"翻译",把对象变成一段 JSON 文本。
案例 2:把 JSON 字符串变回对象(反序列化)
csharp
using System.Text.Json;
string json = "{"Name":"小红","Age":18}";
var person = JsonSerializer.Deserialize
Console.WriteLine($"{person?.Name} 今年 {person?.Age} 岁");
public record Person(string Name, int Age);
Deserialize
案例 3:格式化输出 JSON(带缩进,好看一点)
csharp
using System.Text.Json;
var options = new JsonSerializerOptions { WriteIndented = true };
var data = new { Id = 1, Title = "C#入门" };
string json = JsonSerializer.Serialize(data, options);
Console.WriteLine(json);
WriteIndented = true 让 JSON 自动换行缩进,像上面那样整整齐齐,方便人阅读。

浙公网安备 33010602011771号