代码之家  ›  专栏  ›  技术社区  ›  edison ouyang

招摇过市批注未生成预期结果

  •  2
  • edison ouyang  · 技术社区  · 7 年前

    当我们使用ApiModelProperty定义字符串属性时,我的团队正在使用swagger annotation 1.5.14为文档生成swagger文件,示例如下:

    @ApiModelProperty(example="484799")
    private String accountNumber;
    

    这将生成输出:

    "accountNumber": 484799
    

    是否可以使其生成带有双引号示例值的帐号:

    "accountNumber": "484799"
    

    因为在看示例时,更容易区分字符串值和数字值。

    到目前为止,我们已经尝试了以下内容:

    1. 将转义字符放在双引号中(例如=“\”484799\“”)
    2. 将dataType=“java.lang.String”与示例参数一起使用
    3. 在示例值中留出额外的空间。

    我的环境:Java 1.8、swagger annotation 1.5.14、swagger 2

    提前感谢

    3 回复  |  直到 7 年前
        1
  •  2
  •   edison ouyang    7 年前

    我找到了这个问题的原因,它位于Springfox库中的Swagger2JacksonModule类中,有一个基于值的方法检查:

     private boolean isNotJsonString(final String value) throws IOException {
        // strictly speaking, should also test for equals("null") since {"example": null} would be valid JSON
        // but swagger2 does not support null values
        // and an example value of "null" probably does not make much sense anyway
        return value.startsWith("{")                              // object
            || value.startsWith("[")                          // array
            || "true".equals(value)                           // true
            || "false".equals(value)                          // false
            || JSON_NUMBER_PATTERN.matcher(value).matches();  // number
      }
    

    这只检查值,但忽略注释上声明的数据类型。

        2
  •  0
  •   Santhoshm    6 年前

    您可以在@ApiModelProperty中使用“dataType”元素属性。

    @ApiModelProperty(datatype= "String", example="484799")
    private String accountNumber;
    

    @ApiModelProperty(datatype= "java.lang.String", example="484799")
    private String accountNumber;
    

    如果您使用的是Swagger2,那么@Schema是可选的。 https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations#schema

        3
  •  -1
  •   Sociopath    7 年前

    也许你可以用 String.format() 下面类似的方式。

    String example="484799"
    private String accountNumber = String.format("%s", example)