如何将 @ApiModelProperty dataType 设置为 String 以获取 Swagger 文档

2022-01-22 00:00:00 swagger spring java spring-mvc

我正在使用 Spring MVC(通过 Spring Boot)并使用 swagger-spring-mvc 库集成了 Swagger API 文档.

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;
    }
    ...
}

由于我为此字段使用了 ToStringSerializer,它以 JSON 格式返回 listPrice.toString,换句话说:

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

{
    "listPrice": "USD 10.50"
}

但是,swagger 文档不支持 dataType = "java.lang.String".它将响应模型显示为:

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"
        }
    }
}

我尝试将@ApiModelProperty 注释放在字段和方法上,在这两种情况下都尊重 required 字段,但忽略 dataType 字段.我也尝试过对 dataType 使用String"、string"和java.lang.String",但这些都不起作用.

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.

我是否遗漏了什么,或者这只是 swagger-spring-mvc 库中的一个错误?

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

推荐答案

原来在当前版本的 Swagger Spring MVC 库中完全忽略了 dataType.我在这里找到了一个简短的讨论:

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

看起来它可以包含在版本 2 中.

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

虽然版本 2 说它支持 dataType,但它目前似乎无法正常工作.满足我需求的更好方法是使用直接模型替换来配置文档设置,如下所示:

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);
}

相关文章