You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Newtonsoft Json的ReferenceLoopHandling转为System.Text.Json并解决失效问题

.NET 8中System.Text.Json替代Newtonsoft.Json忽略循环引用的正确配置

你原本的Newtonsoft.Json配置是:

builder.Services
       .AddControllers()
       .AddNewtonsoftJson(o => o.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

你尝试转换的System.Text.Json配置语法本身无误,但未生效,以下是排查和修正建议:

标准正确配置写法

先确认基础配置的标准写法,你的代码逻辑没问题,可直接沿用:

builder.Services
       .AddControllers()
       .AddJsonOptions(options =>
       {
           // 对应Newtonsoft的ReferenceLoopHandling.Ignore
           options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
           // 可选:序列化时忽略null值
           options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
           // 可选:格式化输出
           options.JsonSerializerOptions.WriteIndented = true;
       });

配置未生效的常见排查点

  • 检查是否有配置覆盖:如果项目中存在全局过滤器、自定义JsonConverter或其他地方修改JsonSerializerOptions,可能会覆盖此处设置。
  • 确认序列化场景匹配:如果是手动调用JsonSerializer.Serialize方法(而非控制器返回结果),该全局配置不会生效,需显式传入配置或注入IJsonSerializerOptions获取全局配置。
  • 检查Newtonsoft.Json兼容包:若项目安装了Microsoft.AspNetCore.Mvc.NewtonsoftJson包,默认会优先使用Newtonsoft.Json,此时System.Text.Json配置不生效,需移除该包或明确指定使用System.Text.Json。
  • 验证循环引用场景:确保实体类确实存在循环引用(如A包含B、B包含A),无循环引用时配置不会有明显效果。

配置验证方法

可在控制器中注入IOptions<JsonOptions>验证配置是否正确加载:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    private readonly JsonSerializerOptions _options;

    public TestController(IOptions<JsonOptions> jsonOptions)
    {
        _options = jsonOptions.Value.JsonSerializerOptions;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var isIgnoreCyclesEnabled = _options.ReferenceHandler == ReferenceHandler.IgnoreCycles;
        return Ok(new { IsIgnoreCyclesEnabled = isIgnoreCycles });
    }
}

内容的提问来源于stack exchange,提问作者KeithViking

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 00:54:56