Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set @ApiModelProperty dataType to String for Swagger documentation

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?

like image 970
nerdherd Avatar asked Mar 30 '15 20:03

nerdherd


2 Answers

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);
}
like image 142
nerdherd Avatar answered Nov 19 '22 03:11

nerdherd


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

static {
     SpringDocUtils.getConfig().replaceWithSchema(Money.class, new StringSchema());
}
like image 3
vzhemevko Avatar answered Nov 19 '22 04:11

vzhemevko