首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Java jersey Swagger UI中添加自定义ApiResponse

如何在Java jersey Swagger UI中添加自定义ApiResponse
EN

Stack Overflow用户
提问于 2020-06-29 21:50:28
回答 1查看 465关注 0票数 0

我使用Swagger UI框架来记录API。我拥有的API之一是

代码语言:javascript
运行
复制
@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响应,比如-

@value=@ApiResponse(code= 200,message =“操作成功”,response={"Count“:”int“})

我不想在这里编写一个具有int字段计数的类,因为我有更多的API只有一个或两个字段的自定义响应,并且我不希望为每个自定义响应编写单独的类。

如果这个问题需要进一步的输入,请让我知道。

在此之前,非常感谢您。

EN

回答 1

Stack Overflow用户

发布于 2020-06-30 01:46:17

您可以通过使用泛型类型或对象来执行此操作。对我来说,对象更有意义。

请尝试使用下面的swagger.yml,从中生成的代码将是泛型类型。

代码语言:javascript
运行
复制
openapi: 3.0.1
info:
  title: Swagger Bookstore
  description: 'This is a sample server Bookstore server.'
  version: 1.0.0
servers:
- url: http://bookstore.swagger.io/v2
tags:
- name: book
  description: Everything about your Books
paths:
  /books/count:
    get:
      tags:
      - book
      summary: Get Books count
      description: Fetch total book count
      operationId: getBookCount
      responses:
        200:
          description: successful operation
          content:
            application/json:
              schema:
               $ref: '#/components/schemas/ApiResponse'
        400:
          description: Invalid response
          content: {}
components:
  schemas:
    ApiResponse:
      type: object
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
        response: 
          type: object

您可以看到ApiResponse有一个字段名response,它是作为对象的泛型类型。它可以容纳您指定的任何类型?

代码语言:javascript
运行
复制
response: 
   type: object

由此生成的代码将类似于:

代码语言:javascript
运行
复制
@ApiResponses(value=@ApiResponse(code = 200, message = "Successful operation", response={}))

所以,在这里,response={}可以保存您想要的任何内容。例如response={count=5}或您指定的任何类型。

请尝试这将解决您的问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62639632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档