深入理解.NET 9中JSON序列化的改进与新特性
.NET 9正式发布后,系统性地增强了JSON处理能力。本文将详细探讨.NET 9在JSON序列化领域引入的两项重要改进。
可自定义的缩进配置
在.NET 9之前,JsonSerializerOptions仅提供WriteIndented属性来控制是否格式化输出,但无法自定义缩进的具体形式。新版本引入了两个关键属性:
- IndentChars:指定缩进使用的字符,默认为空格
- IndentSize:指定每层缩进的字符数量,默认为2
这一改进使得开发者能够根据不同场景灵活调整JSON输出格式。
实际应用示例
using System;
using System.Text.Json;
var configuration = new JsonSerializerOptions
{
WriteIndented = true,
IndentChars = "\t",
IndentSize = 1
};
string result = JsonSerializer.Serialize(
new { Message = "Hello World" },
configuration
);
Console.WriteLine(result);
输出结果:
{
"Message": "Hello World"
}
典型使用场景
自定义缩进功能在以下场景中尤为实用:
- 适配第三方系统的日志格式规范
- 满足特定前端框架对JSON格式的严格要求
- 在保持可读性的同时优化传输数据体积
- 与现有代码库的缩进风格保持统一
完整演示代码
using System;
using System.Text.Json;
public class SerializeDemo
{
public static void Main()
{
var employee = new
{
Name = "Bob",
Department = "Engineering",
Technologies = new[] { "C#", "SQL", "Redis" }
};
// 标准格式输出
var standardConfig = new JsonSerializerOptions
{
WriteIndented = true
};
Console.WriteLine("标准格式:");
Console.WriteLine(JsonSerializer.Serialize(employee, standardConfig));
// 采用制表符缩进
var tabConfig = new JsonSerializerOptions
{
WriteIndented = true,
IndentChars = "\t",
IndentSize = 1
};
Console.WriteLine("\n制表符缩进:");
Console.WriteLine(JsonSerializer.Serialize(employee, tabConfig));
// 采用4空格缩进
var spaceConfig = new JsonSerializerOptions
{
WriteIndented = true,
IndentChars = " ",
IndentSize = 4
};
Console.WriteLine("\n四空格缩进:");
Console.WriteLine(JsonSerializer.Serialize(employee, spaceConfig));
}
}
运行结果展示:
标准格式(2空格缩进):
{
"Name": "Bob",
"Department": "Engineering",
"Technologies": [
"C#",
"SQL",
"Redis"
]
}
制表符缩进:
{
"Name": "Bob",
"Department": "Engineering",
"Technologies": [
"C#",
"SQL",
"Redis"
]
}
四空格缩进:
{
"Name": "Bob",
"Department": "Engineering",
"Technologies": [
"C#",
"SQL",
"Redis"
]
}
Web场景专用单例
.NET 9新增了JsonSerializerOptions.Web单例属性,专门为Web应用程序优化。该单例预设了符合Web开发习惯的序列化策略:
- 自动采用camelCase命名策略
- 默认忽略值为null的属性
- 支持字符串形式的数字解析
此特性简化了ASP.NET Core等Web框架的JSON序列化配置。
基本用法
using System.Text.Json;
var payload = new { UserId = 100, Active = false };
string webJson = JsonSerializer.Serialize(
payload,
JsonSerializerOptions.Web
);
Console.WriteLine(webJson);
// 输出: {"userId":100}
实战案例
using System.Text.Json;
public class OrderItem
{
public int ProductId { get; set; }
public string ProductName { get; set; } = "Default Item";
public int Quantity { get; set; } = 0;
public string? Notes { get; set; }
}
public class WebSerializeDemo
{
public static void Main()
{
var order = new OrderItem();
string json = JsonSerializer.Serialize(order, JsonSerializerOptions.Web);
Console.WriteLine(json);
}
}
输出结果:
{"productId":0,"productName":"Default Item"}
分析输出可见:Quantity默认值为0被忽略,Notes为null也被过滤,仅保留了非默认值的属性。
应用价值
JsonSerializerOptions.Web在以下场景极具优势:
- 构建RESTful API时自动生成符合前端约定的JSON格式
- 减少前后端因命名风格差异导致的沟通成本
- 自动过滤无意义的默认值,优化网络传输效率
总结
.NET 9对System.Text.Json的增强主要体现在两个方面:灵活可控的缩进配置以及开箱即用的Web场景优化。这些改进显著提升了开发体验,使JSON序列化更加便捷高效。