2024-09-02 · C# 基础 · 学习笔记

System.Text.Json 使用

System.Text.Json 是 .NET Core 内置的高性能 JSON 库,比 Newtonsoft.Json 更快。但默认配置和 Newtonsoft 有差异,需要注意。

默认大小写敏感,前端一般传 camelCase,要配 JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase。日期格式默认是 ISO 8601。

注意:1) 写 options 为 static 字段复用,不要每次 new;2) JsonSerializer.Serialize 支持泛型;3) 复杂类型用 JsonConverter 自定义。

代码示例

using System.Text.Json;
using System.Text.Json.Serialization;

// 模型
public class User
{
    public string Name { get; set; } = "";
    public int Age { get; set; }
    public DateTime CreateTime { get; set; }
}

// 序列化
var user = new User
{
    Name = "Tom",
    Age = 25,
    CreateTime = DateTime.Now
};

// 默认配置
string json = JsonSerializer.Serialize(user);
Console.WriteLine(json);
// {"Name":"Tom","Age":25,"CreateTime":"2024-09-..."}

// 复用 options(推荐)
static readonly JsonSerializerOptions Options = new()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = true
};

string camelJson = JsonSerializer.Serialize(user, Options);
// {"name":"Tom","age":25,...}

// 反序列化
var back = JsonSerializer.Deserialize<User>(json)!;
Console.WriteLine(back.Name); // Tom
学习小结:以上是我学习这个知识点时的笔记和心得。技术学习没有捷径,多写多练多踩坑,自然就掌握了。如果这篇笔记对你有帮助,欢迎继续看看其他文章。