【问题标题】:How to customize example values in Springfox's Swagger 2 for a JSONObject request body?如何在 Springfox 的 Swagger 2 中为 JSONObject 请求正文自定义示例值?
【发布时间】:2019-02-17 23:10:30
【问题描述】:

我想为我使用 Springfox 的 Swagger (Spring REST API) 制作的 API 文档自定义示例值。

由于请求正文是通过 JQuery AJAX 进行的字符串化 JSON,因此 @RequestParam 是一个字符串。 我尝试了多种“解决方案”,包括@ApiModel@ApiImplicitParams,但都没有奏效。 "string" 似乎永远不会改变。

如何更改示例值?我不介意是否需要手动完成。我只希望该区域显示一个 JSON 对象。

【问题讨论】:

    标签: rest spring-boot swagger-ui swagger-2.0 springfox


    【解决方案1】:

    如果使用对象来描述请求体,可以使用@ApiModelProperty,例如:

    data class RequestBody(
        @ApiModelProperty(example = "John Doe")
        val name: String,
        @ApiModelProperty(example = "Coolstreet 1")
        val address: String
    )
    

    替代方法是使用@Example 和@ExampleProperties,但我发现它们更加混乱。官方参考文档中有一些关于如何使用它们的示例:http://springfox.github.io/springfox/docs/current/#example-application

    提供的示例:

    @RequestMapping(value = "/2031", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "/2031")
    @ApiImplicitParams({
        @ApiImplicitParam(
            name = "contents",
            dataType = "CustomTypeFor2031",
            examples = @io.swagger.annotations.Example(
                value = {
                    @ExampleProperty(value = "{'property': 'test'}", mediaType = "application/json")
                })) 
    })
    public void save(@PathVariable("keyId") String keyId,
                     @PathVariable("id") String id,
                     @RequestBody String contents 
    ) {
    }
    
    public static class CustomTypeFor2031 { 
      private String property;
    
      public String getProperty() {
        return property;
      }
    
      public void setProperty(String property) {
        this.property = property;
      }
    }
    

    【讨论】: