System.Text.Json 嵌套深度问题

关于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;

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Humbunklung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值