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

如何仅在Swagger UI的AnimalResponse响应中隐藏Animal的height属性?

解决方案

针对你的需求——在Swagger UI中仅隐藏AnimalResponse里Animal的height属性,同时保留其他场景下Animal的height显示,可采用以下几种可行方案:

方案一:创建专用DTO子类

通过继承Animal创建专用子类,仅在子类中对height添加@ApiModelProperty(hidden=true),再修改AnimalResponse的animals字段类型为该子类:

// 仅用于AnimalResponse的Animal子类
@ApiModel(value = "AnimalForResponse")
public class AnimalForResponse extends Animal {
    @Override
    @ApiModelProperty(hidden = true)
    public float getHeight() {
        return super.getHeight();
    }
}

// 修改AnimalResponse的字段类型
class AnimalResponse {
    @JsonProperty("animals")
    private List<AnimalForResponse> animals = new ArrayList<>();
    @JsonProperty("someOtherAttributes")
    private List<someOtherAttribute> someOtherAttributes= new ArrayList<>();
}

这种方式逻辑简单直接,通过子类隔离Swagger注解的作用范围,完全不影响原Animal类在其他场景的使用。

方案二:使用Swagger的自定义Schema处理器(SpringDoc/OpenAPI 3)

如果使用SpringDoc(OpenAPI 3),可以通过实现SchemaCustomizer接口,在处理Schema时动态判断上下文,移除AnimalResponse中Animal的height属性:

@Component
public class AnimalSchemaCustomizer implements SchemaCustomizer {
    @Override
    public void customize(Schema schema, SchemaCustomizerContext context) {
        // 检查当前Schema对应类型为Animal,且父Schema是AnimalResponse
        if (Animal.class.equals(context.getType()) && "AnimalResponse".equals(context.getParentSchema().getName())) {
            schema.getProperties().remove("height");
        }
    }
}

该方案无需修改原有实体类结构,通过配置实现条件隐藏,适配性更强。

方案三:旧版Swagger(Springfox)的ModelMapper定制

如果使用的是Springfox(Swagger 2),可以通过自定义ModelMapper来控制模型字段的显示:

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("your.package.path"))
                .paths(PathSelectors.any())
                .build()
                .modelMapper(new ModelMapper() {
                    @Override
                    public Model mapType(Type type, Context context) {
                        Model model = super.mapType(type, context);
                        // 判断当前是否是AnimalResponse下的Animal属性
                        if (type == Animal.class && "AnimalResponse".equals(context.getParentName())) {
                            model.getProperties().remove("height");
                        }
                        return model;
                    }
                });
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:45:30