Swashbuckle自动生成Swagger示例未包含嵌套对象属性如何解决
问题根因
你的Notional类的Amount和Currency属性均为只读属性(仅定义了get访问器,无set访问器),Swashbuckle默认会将只读属性排除在请求体Schema的生成范围之外,所以才会生成空的{}占位示例,而底部Schemas板块能正确展示是因为该板块会扫描类型的所有公共属性,不受请求体规则限制。
另外注意原代码中[JsonContructor]存在拼写错误,正确写法是[JsonConstructor],该错误也可能影响序列化器对类型的识别。
解决方案
你可以任选以下任意一种方式修复:
方案1:给属性添加[JsonInclude]特性(改动最小)
如果你使用的是System.Text.Json作为默认序列化器,直接给只读属性添加[JsonInclude]特性即可,Swashbuckle会识别该特性,将属性纳入请求Schema:
public class Notional { // 修正拼写错误 [JsonConstructor] public Notional(decimal amount, string currency) { Amount = amount; Currency = currency; } public Notional() { Amount = 0; Currency = "XXX"; } [JsonInclude] public decimal Amount { get; } [JsonInclude] public string Currency { get; } }
方案2:显式映射Notional类型的Schema
直接在AddSwaggerGen配置中指定Notional的生成规则,适合不想修改实体类的场景:
using Microsoft.OpenApi.Models; services.AddSwaggerGen(options => { // 显式定义Notional类型的Schema结构 options.MapType<Notional>(() => new OpenApiSchema { Type = "object", Properties = new Dictionary<string, OpenApiSchema> { { "Amount", new OpenApiSchema { Type = "number", Format = "decimal", Default = new OpenApiDecimal(0) } }, { "Currency", new OpenApiSchema { Type = "string", Default = new OpenApiString("XXX") } } } }); });
方案3:添加全局Schema过滤器(通用方案)
如果项目中有大量类似的只读属性类需要处理,可以写一个全局过滤器统一处理,避免逐个配置:
- 先定义过滤器类:
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Reflection; public class IncludeReadOnlyPropertiesFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { // 仅处理属性为空的自定义类型 if (schema.Properties == null || !schema.Properties.Any()) { var publicProperties = context.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in publicProperties) { var propertySchema = context.SchemaGenerator.GenerateSchema( property.PropertyType, context.SchemaRepository ); schema.Properties.Add(property.Name, propertySchema); } } } }
- 在Swagger配置中注册过滤器:
services.AddSwaggerGen(options => { options.SchemaFilter<IncludeReadOnlyPropertiesFilter>(); });
修改完成后重新启动项目,Swagger UI就会生成你预期的嵌套对象示例。
内容的提问来源于stack exchange,提问作者Bradley Uffner
相关产品推荐
相关产品推荐

