首页 > 解决方案 > 将一种方法迁移到 System.Text.Json

问题描述

我在 .net core 3.1 中添加了 NewtonsoftJson 作为中间件。我很想转移到新的 System.Text.Json 序列化程序。

我不能只是跳过,但有没有办法以某种方法使用 System.Text.Json 中的那个。或多或少这是我需要加快速度的一个。

补充:我在启动

services.AddControllers(options => options.RespectBrowserAcceptHeader = true)
        .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling =
                Newtonsoft.Json.ReferenceLoopHandling.Ignore);

我的迁移问题是我不能一次将其更改为 System.Text.Json。因此,如果我可以更改一个控制器或仅更改控制器中的一种方法以使用 System.Text.Json 版本,这将解决我的问题。

标签: c#json.net-coresystem.text.json

解决方案


从 .Net 6 开始,System.Text.Json 支持忽略循环引用,可以这样使用

services.AddControllers()
.AddJsonOptions(options => {options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;});

有关更多信息,请参见此处: https ://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-preserve-references?pivots=dotnet-6-0


推荐阅读