Swagger Schema的oneOf未生成Object和List类型问题求助
问题分析与解决方案
问题总结
你期望Swagger生成包含id(int32类型)和teste(支持object、integer、array三种类型之一)的Employee模型,但实际生成结果为空对象,且List类型未正确显示。
核心问题点
- 依赖版本冲突:单独引入的
swagger-annotations 2.1.6与springdoc-openapi-starter-webmvc-ui 2.2.0自带的Swagger依赖版本不兼容,导致注解解析异常。 - List类型未正确定义:
@Schema的oneOf参数中直接传入List.class无法被OpenAPI规范识别为数组类型,泛型类型在运行时会被擦除,必须明确指定数组的元素结构。 - 缺少必要字段与访问器:代码中未实现
id字段,且varDeTeste字段没有getter/setter方法,SpringDoc无法通过反射获取字段信息,导致模型生成为空。
修正后的代码与配置
1. 调整Maven依赖
移除单独的swagger-annotations依赖,使用springdoc-starter自带的兼容版本:
<dependencies> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.2.0</version> </dependency> </dependencies>
2. 修改Employee类代码
补充id字段,修正teste字段的oneOf配置,同时添加必要的getter/setter:
import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Schema; @Schema(description = "Description of Employee") public class Employee { @Schema(type = "integer", format = "int32", description = "Unique identifier of the employee") private Integer id; @Schema( name = "teste", description = "Field supporting multiple types: object, integer or array of objects", oneOf = {Object.class, Integer.class}, oneOfSchemas = { @Schema(implementation = Object.class), @Schema(type = "integer"), @ArraySchema(schema = @Schema(type = "object")) // 若数组元素为其他类型,可修改这里的type } ) @JsonProperty("teste") private Object varDeTeste; // Getter & Setter public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Object getVarDeTeste() { return varDeTeste; } public void setVarDeTeste(Object varDeTeste) { this.varDeTeste = varDeTeste; } }
关键说明
- 数组类型定义:使用
@ArraySchema明确指定数组的元素类型,解决泛型擦除导致的List无法识别问题。如果你的数组元素是特定类型(如String),可将@Schema(type = "object")改为@Schema(type = "string")。 - 依赖兼容性:SpringDoc starter已经集成了所需的Swagger核心依赖,单独引入可能引发版本冲突,务必移除独立的
swagger-annotations依赖。 - 访问器方法:SpringDoc通过反射读取字段信息,必须为每个字段提供getter/setter,否则无法生成正确的模型结构。
内容的提问来源于stack exchange,提问作者Fabricio CR
相关产品推荐
相关产品推荐

