.NET 9官方文档:https://learn.microsoft.com/zh-cn/dotnet/core/whats-new/dotnet-9/overview
C# 13官方文档:https://learn.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-13
序列化
在System.Text.Json中,.NET 9 提供了用于序列化 JSON 的新选项和新的单一实例,可以更轻松地使用 Web 默认值进行序列化。
序列化 — 缩进选项
在进行Json配置的JsonSerializerOptions包括新的属性,可支持自定义写入Json的缩进字符和缩进大小
举例,这是正常操作数据库类响应的Json格式
动作方法代码:
C#
[HttpGet]
public async Task<string> GetSingle(long id)
{
var response = await _context.Songs.FindAsync(id);
return JsonSerializer.Serialize(response);
}
响应格式:
JSON
{"ID":2,"SongId":"00054233f0146ff517d27989201f2a9a","ArtistId":"a581aaeb73a9ce7f6806eb1e56e319b6","PublishTime":"27/4/2005","SongInitPlays":19834,"Language":2,"Gender":3}
而这是配置了自定义缩进字符和缩进大小JsonSerializerOptions的序列化后的代码
动作方法代码:
C#
[HttpGet]
public async Task<string> GetSingle(long id)
{
var response = await _context.Songs.FindAsync(id);
JsonSerializerOptions options = new()
{
//打印得非常清晰
WriteIndented = true,
//定义启用 WriteIndented 时使用的缩进字符。 默认为空格字符。
IndentCharacter = '\t',
//定义启用 WriteIndented 时使用的缩进大小。 默认值为 2
IndentSize = 2
};
return JsonSerializer.Serialize(response, options);
}
响应格式:
JSON
{
"ID": 2,
"SongId": "00054233f0146ff517d27989201f2a9a",
"ArtistId": "a581aaeb73a9ce7f6806eb1e56e319b6",
"PublishTime": "27/4/2005",
"SongInitPlays": 19834,
"Language": 2,
"Gender": 3
}
序列化 — 默认 Web 选项
如果要使用 ASP.NET Core 用于 Web 应用的默认选项进行序列化,请使用新的 JsonSerializerOptions.Web 单一实例。
额,这里我觉得 跟正常打印其实没什么区别,所以下面就没有放Json格式的代码了…
C#
[HttpGet]
public async Task<string> GetSingleJson(long id)
{
var response = await _context.Songs.FindAsync(id);
return JsonSerializer.Serialize(response, JsonSerializerOptions.Web);
}
Params类型
C# 13 扩展了Params关键字,使其适用于可以通过集合表达式构造的任何类型。无论是编写方法还是调用方法,都增加了灵活性。
![](https://ichiblog.cn/wp-content/uploads/2024/11/图片.png)
C#中Params的用法:https://blog.csdn.net/Ginny97/article/details/103251391