SwaggerUI中JsonIgnore特性致模型属性未在JSON Schema显示如何解决?
问题解决方法
你遇到的问题是因为JsonIgnoreCondition.WhenWritingNull会让JSON Schema生成器默认将该字段排除在外。要保留字段在Schema中,同时维持null值不序列化的逻辑,可以按以下方式处理:
1. 直接使用JsonSchemaGenerator的场景
如果是通过System.Text.Json.Schema包的JsonSchemaGenerator生成Schema,可修改生成器设置,忽略JsonIgnore的WhenWritingNull条件:
using System.Text.Json.Schema; var generatorSettings = new JsonSchemaGeneratorSettings { // 让生成器不遵循WhenWritingNull的忽略规则,确保字段被纳入Schema IgnoreConditions = JsonIgnoreCondition.Never }; var schemaGenerator = new JsonSchemaGenerator(generatorSettings); var myResponseSchema = schemaGenerator.Generate(typeof(MyResponse));
这样生成的Schema会包含MyField,且该字段不会出现在required数组中(符合可选字段定义),同时序列化时null值依然会被忽略。
2. ASP.NET Core Swagger/OpenAPI场景
如果是Swagger文档中看不到该字段,可通过以下两种方式处理:
方式一:调整SwaggerGen基础配置
services.AddSwaggerGen(options => { // 关闭可空属性的自动忽略逻辑 options.SchemaGeneratorOptions.IgnoreNullableProperties = false; });
方式二:自定义Schema过滤器强制添加字段
若基础配置不生效,可编写过滤器手动识别带有WhenWritingNull标记的字段并加入Schema:
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Reflection; using System.Text.Json.Serialization; public class IncludeNullIgnoredFieldsFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { var targetProperties = context.Type.GetProperties() .Where(p => p.GetCustomAttribute<JsonIgnoreAttribute>()?.Condition == JsonIgnoreCondition.WhenWritingNull); foreach (var prop in targetProperties) { // 获取字段的JSON名称(优先使用JsonPropertyName指定的名称) var jsonFieldName = prop.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name ?? prop.Name; // 生成字段对应的Schema var fieldSchema = context.SchemaGenerator.GenerateSchema(prop.PropertyType, context.SchemaRepository); // 将字段加入当前Schema的properties集合 if (!schema.Properties.ContainsKey(jsonFieldName)) { schema.Properties.Add(jsonFieldName, fieldSchema); } } } }
注册该过滤器:
services.AddSwaggerGen(options => { options.SchemaFilter<IncludeNullIgnoredFieldsFilter>(); });
关键说明
无论哪种方式,最终生成的Schema中MyField会出现在properties里,且不会被加入required数组(因为它是可选字段),同时完全保留"null值不序列化"的原有逻辑。
内容的提问来源于stack exchange,提问作者user149691
相关产品推荐
相关产品推荐

