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.

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 cyc

系统文本Json。JsonException:检测到可能的对象循环。这可能是由于循环造成的,或者如果对象深度大于允许的最大深度32。考虑使用引用处理程序。在JsonSerializerOptions上保留以支持循环。

在系统中。文本Json。ThrowHelper。ThrowJsonException_SerializerCycledtected(Int32 maxDepth)

 

这是由于进行了对象嵌套或ef 查询进行了预加载(关联加载)引起的,就像解释说的“对象循环”,层级太深解析不了。

解决方法:

  1. 添加 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包
  2. Startup中添加服务,忽略循环引用
    //解决Json序列化的时候没有对中文进行处理
                services.AddControllersWithViews().AddJsonOptions(cfg =>
                {
                    cfg.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                }).AddNewtonsoftJson(option =>
                option.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                );

     

或者
通过另外创建一个类对查询到的数据进行封装后再返还。

posted @ 2022-02-19 17:50  lunawzh  阅读(555)  评论(0编辑  收藏  举报