System.Text.Json
命名空间提供了用于将数据^序列化为 JSON
和从 JSON
反^序列化的功能。在 ``.NET 8中,对
System.Text.Json` 的序列化和反序列化功能进行了许多改进。
源代码生成器
.NET 8
包括 System.Text.Json
源代码生成器的增强功能,旨在使 Native AOT
(Ahead-Of-Time
)体验与基于反射的序列化器相媲美。这很重要,因为现在你可以选择 System.Text.Json
的源代码生成器。要查看 System.Text.Json
中反射与源代码生成的比较,请查阅比较文档。
接口层次结构
.NET 8
增加了对从接口层次结构^序列化属性的支持。以下是演示此功能的代码示例。
ICar car = new MyCar { Color = "Red", NumberOfWheels = 4 };
JsonSerializer.Serialize(car); // {"Color":"Red","NumberOfWheels":4}
public interface IVehicle
{
public string Color { get; set; }
}
public interface ICar : IVehicle
{
public int NumberOfWheels { get; set; }
}
public class MyCar : ICar
{
public string Color { get; set; }
public int NumberOfWheels { get; set; }
}
命名策略
新增了两种新的命名策略:snake_case
和 kebab-case
。你可以像下面所示使用它们:
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
JsonSerializer.Serialize(new { CreationTime = new DateTime(2023,11,6) }, options); // {"creation_time":"2023-11-06T00:00:00"}
只读属性
在 .NET 8
中,你可以将数据反序列化到只读字段或属性上。可以通过将 PreferredObjectCreationHandling
设置为 JsonObjectCreationHandling.Populate
来全局启用此功能。你还可以通过在类或其成员上添加 [JsonObjectCreationHandling(JsonObjectCreationHandling.Populate)] 属性来启用此功能。以下是一个示例:
using System.Text.Json;
using System.Text.Json.Serialization;
var book = JsonSerializer.Deserialize<Book>("""{"Contributors":["John Doe"],"Author":{"Name":"Sample Author"}}""")!;
Console.WriteLine(JsonSerializer.Serialize(book));
class Author
{
public required string Name { get; set; }
}
[JsonObjectCreationHandling(JsonObjectCreationHandling.Populate)]
class Book
{
// Both of these properties are read-only.
public List<string> Contributors { get; } = new();
public Author Author { get; } = new() {Name = "Undefined"};
}
在 .NET 8
之前,产生以下输出:
{ "Contributors": [], "Author": { "Name": "Undefined" } }
在 .NET 8
中,输出现在看起来像这样:
{ "Contributors": ["John Doe"], "Author": { "Name": "Sample Author" } }
禁用基于反射的默认设置
关于序列化的一个好处是,现在你可以默认禁用基于反射的^序列化器。要禁用默认的基于反射的序列化,请在项目文件中将 JsonSerializerIsReflectionEnabledByDefault MSBuild
属性设置为 false
。
流式反序列化 API
.NET 8
包括新的 IAsyncEnumerable<T>
流式反序列化扩展方法。这些新的扩展方法调用流式 API
并返回 IAsyncEnumerable<T>
。以下是使用此新功能的示例代码。
const string RequestUri = "https://yourwebsite.com/api/saas/tenants?skipCount=0&maxResultCount=10";
using var client = new HttpClient();
IAsyncEnumerable<Tenant> tenants = client.GetFromJsonAsAsyncEnumerable<Tenant>(RequestUri);
await foreach (Tenant tenant in tenants)
{
Console.WriteLine($"* '{tenant.name}' uses '{tenant.editionName}' edition");
}
如果您想查看完整的列表,你可以在 .NET 8
的新特性文档中找到详细信息。
Comments