关于System.Text.Json
System.Text.Json是微软.net Core 3.0开始提供的Json处理库,主要包含JSON序列化和反序列化等功能,类似我们耳熟能详的Newtonsoft.Json。
System.Text.Json命名空间的官方描述:“提供高性能、低分配和标准兼容的功能,以处理 JavaScript 对象表示法 (JSON),其中包括将对象序列化为 JSON 文本以及将 JSON 文本反序列化为对象(内置 UTF-8 支持)。 它还提供类型以用于读取和写入编码为 UTF-8 的 JSON 文本,以及用于创建内存中文档对象模型 (DOM) 以在数据的结构化视图中随机访问 JSON 元素。”
问题
实际开发过程当中,因JSON对象套路嵌套太深,可能会出现“检测到不支持的可能对象循环。这可能是由于周期或物体深度大于最大允许深度32。”
套路太深,譬如我的一个asp.net core应用,System.Text.Json直接罢工报异常了:
System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.
解决方法
方法一
用回老朋友Newtonsoft.Json,以Web的MVC开发为例:
(1)通过NuGet添加 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包;
(2)Startup中添加服务,如WebAPI项目则为WebApiStartup.cs 文件,在方法:
public static void CustomConfigureServices(IServiceCollection services, IConfiguration configuration)
中忽略循环引用
services.AddControllers().AddNewtonsoftJson(options => {
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
方法二
直接修改System.Text.Json设置,找到Startup,如WebAPI项目则为WebApiStartup.cs 文件,public static void CustomConfigureServices(IServiceCollection services, IConfiguration configuration)方法加入如下代码:
// 增加对多重JSON嵌套支持,默认32重。
options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;