jax-rs – 使用swagger的注释在Swagger UI中显示XML / JSON样本值

前端之家收集整理的这篇文章主要介绍了jax-rs – 使用swagger的注释在Swagger UI中显示XML / JSON样本值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在实现基于Jersey的REST API并使用swagger生成基于 HTML的文档.我正在使用swagger的注释来读取和扫描资源以生成文档.我已使用@ApiResponse注释为每个资源指定了响应,如下所示:
  1. @Path("/hello")
  2. @Api(value = "Hello World" )
  3. public class HelloRest
  4. {
  5. @GET
  6. @ApiOperation(value="Hello world",httpMethod="GET")
  7. @ApiResponses(value={ @ApiResponse(code = 200,message = "Success",response = WebservicesErrorResponse.class,reference = "C:/Desktop/hello.json")
  8. @ApiResponse(code = 404,message = "Not found",response = WebservicesErrorResponse.class)})
  9. @Produces({"application/json","application/xml"})
  10. public Response helloWorld()
  11. {
  12. return Response.status(WebservicesCommonTypes.SUCCESS).entity("Hello rest API").build();
  13. }
  14. }

它工作正常,它生成基于HTML的文档,如下所示:

因为它显示响应代码404时响应的完整结构(模型和示例值).在示例值中,它不显示值,仅显示模型的每个参数的类型.

我想展示响应的示例示例模式,以便客户端可以理解每个响应的确切响应.我研究了它,我发现有一个属性

@ApiResponse(reference =“”) – 指定对响应类型的引用.指定的引用可以是本地引用,也可以是远程引用,将按原样使用,并将覆盖任何指定的response()类.

我尝试了它,并为我的sample.json文件提供了如下路径:

  1. @ApiResponse(code = 200,response = WebServicesErrorResponse,reference = "http://localhost:9001/myinstanceofapplication/html/api-doc/hello.json")

我还试图给出另一条路径,就像下面的本地路径一样:

  1. @ApiResponse(code = 200,reference = "C:/Desktop/hello.json")

但是当swagger为它生成文档时,它会给出以下结果:

显示C:/Desktop/hello.json未定义!

我已经研究并尝试了很多解决方案,但无法正确引用它.我发现这是https://github.com/swagger-api/swagger-ui/issues/1700https://github.com/swagger-api/swagger-js/issues/606的问题.

那么我如何使用@ApiResponse的引用属性来表示该样式的XML / JSON swagger UI.我的模型类如下:

  1. @XmlRootElement(name="response")
  2. @XmlAccessorType(XmlAccessType.FIELD)
  3. public class WebservicesErrorResponse
  4. {
  5. @XmlElement
  6. private int code;
  7.  
  8. @XmlElement
  9. private String message;
  10.  
  11. public WebservicesErrorResponse(){ }
  12.  
  13.  
  14. public WebservicesErrorResponse(int code,String message)
  15. {
  16. this.code = code;
  17. this.message = message;
  18. }
  19.  
  20. public int getCode()
  21. {
  22. return code;
  23. }
  24. public void setCode(int code)
  25. {
  26. this.code = code;
  27. }
  28.  
  29. public String getMessage()
  30. {
  31. return message;
  32. }
  33. public void setMessage(String message)
  34. {
  35. this.message = message;
  36. }
  37. }

我想在swagger UI中显示以下示例XML:

  1. <?xml version="1.0"?>
  2. <response>
  3. <code>200</code>
  4. <message>success</message>
  5. </response>
您需要使用@ApiModel和@ApiModelProperty注释注释您的模型类(而不是API资源/方法!)作为 described here.

对于您想要实现的目标,可能足以注释您的模型成员,如下所示:

  1. @ApiModelProperty(example = "200")
  2. @XmlElement
  3. private int code;
  4.  
  5. @ApiModelProperty(example = "success")
  6. @XmlElement
  7. private String message;

如果这不起作用,请尝试将注释放在getter上(我不太熟悉这方面的XML方面,只为JSON做过).

猜你在找的XML相关文章