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

OpenAPI3能否无需创建类即可标注Schema?Swagger迁移场景问题

正确实现方案

你可以直接通过@Schema注解的properties属性直接定义返回结构,无需额外创建响应类,写法如下:

@GET
@Path("/isServerUp")
@SubscriberAllowed({"active", "standby"})
@Produces("application/json; charset=UTF-8")
@Operation(
    summary = "Is Server Up?",
    description = "Returns a boolean representing whether the server is up",
    responses = {
        @ApiResponse(
            responseCode = "200",
            description = "Success",
            content = @Content(schema = @Schema(
                type = "object",
                description = "服务器运行状态响应",
                properties = {
                    @Schema.Property(
                        name = "isServerUp",
                        type = "boolean",
                        description = "True if Server is up"
                    )
                }
            ))
        )
    },
    tags = "Admin"
)
public JSONObject isServerUp() throws RESTException {
    Boolean isServerUp = Server.instance().isServerUp();
    JSONObject result = new JSONObject();
    result.put("isServerUp", isServerUp);
    return result;
}

说明

  • 上述写法生成的openapi.yaml完全符合你预期的结构,schema的类型、属性、描述都和要求一致
  • 即使是更复杂的嵌套JSON结构,也可以通过在@Schema.Property中继续嵌套properties属性实现,全程不需要创建额外的POJO类
  • 你之前的变通方案存在结构不匹配问题:schema的type设为boolean,但实际接口返回的是对象类型,会导致文档和实际接口返回不一致,不建议使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:54:02