如何注解配置让RestController返回的Page<Foo>生成正确API响应?
解决方案
要同时保留content-type配置和正确生成Page结构的Swagger Schema,你需要放弃使用array = @ArraySchema配置,直接在@Content的schema中指定Page类型,并关联泛型参数Foo:
方法一:直接指定Page类并关联泛型
@ApiResponses(value = { @ApiResponse( responseCode = "200", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema( implementation = Page.class, subTypes = @Subtype(Foo.class) // 关联泛型类型Foo ) ), description = "The request has succeeded") })
这种方式会让Swagger自动解析Page的结构(包含data、totalElements、totalPages等字段),同时识别data字段是Foo类型的数组。
方法二:使用自定义分页DTO(推荐)
如果你的项目中有自定义的分页响应类(比如PageFoo,明确包含List<Foo> data及其他分页属性),直接指定该类作为schema实现:
@ApiResponses(value = { @ApiResponse( responseCode = "200", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = PageFoo.class) ), description = "The request has succeeded") })
自定义DTO的结构更清晰,Swagger能直接解析出data -> [{Foo}]的嵌套结构,也便于统一分页响应格式。
方法三:手动定义Page结构字段
如果需要更精细的控制,可以手动配置Page的所有属性:
@ApiResponses(value = { @ApiResponse( responseCode = "200", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema( type = "object", properties = { @Property(name = "data", array = @ArraySchema(schema = @Schema(implementation = Foo.class))), @Property(name = "totalElements", type = "integer"), @Property(name = "totalPages", type = "integer"), @Property(name = "size", type = "integer"), @Property(name = "number", type = "integer") // 按需添加其他分页属性 } ) ), description = "The request has succeeded") })
为什么原来的配置不行?
你之前用array = @ArraySchema会强制Swagger生成纯数组的响应结构,但Page本身是一个包含数组字段的对象,而非数组本身,所以必须直接配置schema为Page类型,而非使用array属性。
内容的提问来源于stack exchange,提问作者user19282140
相关产品推荐
相关产品推荐

