How to set @ApiModelProperty dataType to String for Swagger documentation

23,734

Solution 1

Turns out that dataType is completely ignored in the current version of the Swagger Spring MVC library. I found a short discussion on it here:

https://github.com/springfox/springfox/issues/602

Looks like it could be included in version 2 once that is out.

EDIT: Although version 2 says it supports dataType, it doesn't appear to be working at this time. A better approach for my needs is to configure the documentation settings with a direct model substitution like this:

@Bean
public Docket swaggerSpringMvcPlugin() {
    return new Docket(DocumentationType.SWAGGER_2)
            .directModelSubstitute(Money.class, String.class);
}

Solution 2

For OpenApi (Swagger 3.0) and SpringDoc the following global configuration could be used.

static {
     SpringDocUtils.getConfig().replaceWithSchema(Money.class, new StringSchema());
}
Share:
23,734
nerdherd
Author by

nerdherd

Updated on November 11, 2020

Comments

  • nerdherd
    nerdherd over 3 years

    I am using Spring MVC (via Spring Boot) and have integrated Swagger API documentation using the swagger-spring-mvc library.

    I have a class that looks something like this:

    @ApiModel
    public class CartItem {
        ...
        private Money listPrice; // joda money class
    
        @JsonSerialize(using = ToStringSerializer.class)
        @ApiModelProperty(required = true, dataType = "java.lang.String")
        public Money getListPrice() {
            return listPrice;
        }
        ...
    }
    

    Since I'm using the ToStringSerializer for this field, it's returning listPrice.toString in the JSON, in other words:

    {
        "listPrice": "USD 10.50"
    }
    

    However, the swagger documentation is not honoring the dataType = "java.lang.String". It shows the response model as:

    "CartItem": {
        "description": "",
        "id": "CartItem",
        "properties": {
            "listPrice": {
                "required": false,
                "type": "Money"
            }
        }
    }
    

    I have tried putting the @ApiModelProperty annotation on the field as well as the method, and in both cases the required field is respected, but the dataType field is ignored. I have also tried using "String", "string", and "java.lang.String" for the dataType but none of those have worked.

    Am I missing something, or is this just a bug in the swagger-spring-mvc library?