edison ouyang
edison ouyang

Reputation: 109

Swagger annotation does not produce expected result

My team is using swagger annotation 1.5.14 to generate the swagger file for the documentation, when we define a string property with ApiModelProperty and example:

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

This generates the output:

"accountNumber": 484799

Is it possible to make it generate the account number with example value double quoted:

"accountNumber": "484799"

Since it will be easier to tell between string value and number value when look at the example.

Following are we have tried so far:

  1. put the escape character for double quote (example = "\"484799\"")
  2. use dataType = "java.lang.String" with example parameter
  3. Leave extra space in the example value.

My environment: Java 1.8, swagger annotation 1.5.14, swagger 2

Thanks in advance

Upvotes: 2

Views: 2431

Answers (3)

Santhoshm
Santhoshm

Reputation: 74

You can use 'dataType' element property in @ApiModelProperty.

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

or

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

If you are using Swagger2, then @Schema is option. https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations#schema

Upvotes: 1

edison ouyang
edison ouyang

Reputation: 109

I find the cause for this issue, it is in the Springfox library, the class Swagger2JacksonModule, there is a method checking based on the value:

 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
  }

This checks the value only but ignores the dataType declared on the annotation.

Upvotes: 2

Santhoshm
Santhoshm

Reputation: 74

Maybe you can use String.format() something in a similar fashion below.

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

Upvotes: -1

Related Questions