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

Java Jersey Swagger UI如何添加自定义ApiResponse(无需实体类)

问题描述

我正在使用Swagger UI框架进行API文档编制。现有一个API接口:

@GET 
@Path("/books/count") 
@Produces(MediaType.APPLICATION_JSON) 
@ApiOperation(value = "Get total book count in system") 
@ApiResponses(value=@ApiResponse(code = 200, message = "Successful operation", response=**need custom response here**))
public Response getBookCount(){
    int count = bookService.getCount();
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("Count", count);
    return Response.status(Status.OK).entity(jsonObj.toString()).build();
}

该API返回一个包含Count字段的JSON对象。我希望在Swagger UI的@ApiResponse中设置类似如下的自定义响应:

@ApiResponses(value=@ApiResponse(code = 200, message = "Successful operation", response={"Count" : "int"}))

由于还有多个仅含1-2个字段的自定义响应API,我不想为每个接口单独创建实体类,请问是否可行?


解决方案

当然可行!没必要为每个简单响应单独创建实体类,根据你使用的Swagger版本,这里有几种灵活的解决方案:

方案1:使用Swagger 2.x注解(io.swagger.annotations包)

如果你还在使用Swagger 2.x的传统注解,可以试试这两种方法:

方法A:用Map.class结合注解定义结构

把response指定为Map.class,再通过@ApiModel和@ApiModelProperty来明确字段的类型和描述:

@GET 
@Path("/books/count") 
@Produces(MediaType.APPLICATION_JSON) 
@ApiOperation(value = "Get total book count in system") 
@ApiResponses(value = {
    @ApiResponse(code = 200, 
                 message = "Successful operation", 
                 response = Map.class,
                 responseContainer = "Map")
})
@ApiModel(value = "BookCountResponse", description = "Response containing total book count")
@ApiModelProperty(dataType = "int", name = "Count", value = "Total number of books in the system")
public Response getBookCount(){
    // 原有业务代码
}

这样Swagger UI就能正确展示包含Count(整数类型)字段的响应结构了。

方法B:指定String.class并添加JSON示例

如果不需要严格的类型校验,只是想直观展示响应格式,可以把response设为String.class,然后在examples属性里直接写JSON示例:

@ApiResponses(value = {
    @ApiResponse(code = 200, 
                 message = "Successful operation", 
                 response = String.class,
                 examples = @Example(value = @ExampleProperty(mediaType = "application/json", value = "{\"Count\": 100}")))
})

这种方式简单直接,适合快速定义小字段的响应示例。

方案2:升级到OpenAPI 3.x注解(io.swagger.v3.oas.annotations包)

如果你的项目允许升级到更现代的OpenAPI 3.x注解,这会是最灵活的选择——可以直接在@ApiResponse里定义响应结构,完全不需要实体类:

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;

@GET 
@Path("/books/count") 
@Produces(MediaType.APPLICATION_JSON) 
@Operation(summary = "Get total book count in system")
@ApiResponse(responseCode = "200", 
             description = "Successful operation",
             content = @Content(mediaType = "application/json",
                                schema = @Schema(type = "object",
                                                properties = {
                                                    @Schema(name = "Count", type = "integer", description = "Total number of books in the system")
                                                })))
public Response getBookCount(){
    // 原有业务代码
}

这种方式支持直接定义任意简单对象的结构,完美适配你这种有多个小字段响应的场景,还能清晰展示每个字段的类型和描述。

小提示

  • 如果你用的是Jersey或其他JAX-RS实现,要注意Swagger依赖版本和注解版本的兼容性,避免出现奇怪的问题。
  • 对于多个结构类似的简单响应,你还可以复用@Schema定义,比如提取一个公共的字段模板,减少重复代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:07:37