How to set @ApiModelProperty dataType to String fo

2020-04-02 06:27发布

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?

2条回答
虎瘦雄心在
2楼-- · 2020-04-02 06:54
@ApiModel
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Model {
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonProperty("myDate")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private final LocalDateTime myDateTime;

}
查看更多
成全新的幸福
3楼-- · 2020-04-02 07:16

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);
}
查看更多
登录 后发表回答