【问题标题】:Migrate one method to System.Text.Json将一种方法迁移到 System.Text.Json
【发布时间】:2020-09-13 18:34:04
【问题描述】:

我在 .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-core system.text.json


【解决方案1】:

从.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

【讨论】:

    【解决方案2】:

    目前在 .Net 3.1 中没有实现。当前的迁移指南 How to migrate from Newtonsoft.Json to System.Text.Json: Scenarios that JsonSerializer currently doesn't support : Preserve object references and handle loops 指出:

    Newtonsoft.Json 还具有 ReferenceLoopHandling 设置,可让您忽略循环引用而不是引发异常。

    System.Text.Json只支持按值序列化,循环引用会抛出异常。

    另请参阅 github 问题 System.Text.Json Reference Loop Handling #29900,其中声明这是一个“已知限制” - 但当前的发布里程碑是 .Net Core 5.0。建议的规范在这里:https://github.com/dotnet/runtime/blob/master/src/libraries/System.Text.Json/docs/ReferenceHandling_spec.md

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多