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

如何配置Swagger同时兼容System.Text.Json与Newtonsoft.Json

Swagger同时兼容Newtonsoft.Json与System.Text.Json序列化特性配置方案

核心原理

Swashbuckle默认全局使用单一序列化规则生成Schema,开启AddSwaggerGenNewtonsoftSupport会全量替换Schema生成逻辑为Newtonsoft.Json规则,无法自动区分两类模型。通过自定义Schema过滤器,按属性维度判断标注的序列化特性,分别匹配对应命名规则即可实现兼容。

操作步骤

  • 前置依赖检查
    确保项目已安装以下NuGet包,无需额外引入其他第三方依赖:

    • Swashbuckle.AspNetCore.SwaggerGen(Swagger基础生成组件)
    • Swashbuckle.AspNetCore.Newtonsoft(仅需引入包,不要调用全局AddSwaggerGenNewtonsoftSupport()方法)
  • 实现自定义Schema过滤器
    新建类实现ISchemaFilter接口,遍历模型属性时优先识别Newtonsoft.Json的[JsonProperty]特性,无该特性时按System.Text.Json默认规则识别[JsonPropertyName]特性,同步修正Schema中的属性键名与必填项配置:

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json;
using System.Text.Json.Serialization;
using System.Reflection;

public class DualJsonCompatibleSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema.Properties == null || context.Type == null) return;

        foreach (var prop in context.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            // 匹配当前属性在Schema中的默认条目(和System.Text.Json默认生成规则对齐)
            var defaultMatched = schema.Properties
                .FirstOrDefault(p => p.Key.Equals(prop.Name, StringComparison.OrdinalIgnoreCase));
            if (defaultMatched.Value == null) continue;

            // 优先处理Newtonsoft.Json的JsonProperty配置
            var newtonsoftAttr = prop.GetCustomAttribute<JsonPropertyAttribute>();
            if (newtonsoftAttr != null && !string.IsNullOrEmpty(newtonsoftAttr.PropertyName))
            {
                schema.Properties.Remove(defaultMatched.Key);
                schema.Properties.Add(newtonsoftAttr.PropertyName, defaultMatched.Value);
                // 同步修正必填项集合中的键名
                if (schema.Required?.Contains(defaultMatched.Key) == true)
                {
                    schema.Required.Remove(defaultMatched.Key);
                    schema.Required.Add(newtonsoftAttr.PropertyName);
                }
                continue;
            }

            // 处理System.Text.Json的JsonPropertyName配置
            var stjAttr = prop.GetCustomAttribute<JsonPropertyNameAttribute>();
            if (stjAttr != null && !string.IsNullOrEmpty(stjAttr.Name))
            {
                schema.Properties.Remove(defaultMatched.Key);
                schema.Properties.Add(stjAttr.Name, defaultMatched.Value);
                if (schema.Required?.Contains(defaultMatched.Key) == true)
                {
                    schema.Required.Remove(defaultMatched.Key);
                    schema.Required.Add(stjAttr.Name);
                }
            }
        }
    }
}
  • 注册过滤器
    在Program.cs的Swagger配置中注册自定义过滤器,不要添加AddSwaggerGenNewtonsoftSupport()全局配置:
builder.Services.AddSwaggerGen(options =>
{
    // 原有Swagger配置(文档信息、注释加载等)保持不变
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "业务API", Version = "v1" });

    // 注册双兼容Schema过滤器
    options.SchemaFilter<DualJsonCompatibleSchemaFilter>();
});

扩展说明

如果外部依赖模型还使用了Newtonsoft.Json的其他特性(如[JsonIgnore]、自定义JsonConverter、枚举序列化规则),直接在上述过滤器中扩展对应判断逻辑即可,核心原则是:对每个属性/类型优先判断是否存在Newtonsoft序列化特性,存在则按Newtonsoft规则处理,否则沿用System.Text.Json的默认生成结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 12:57:14