如何将@ApiModelProperty数据类型设置为字符串以进行 Swagger 文档

2022-09-03 02:27:32

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

我有一个看起来像这样的类:

@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,换句话说:

{
    "listPrice": "USD 10.50"
}

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

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

我尝试过将@ApiModelProperty注释和方法放在字段上,在这两种情况下,字段都被尊重,但字段被忽略。我也尝试过使用“String”,“string”和“java.lang.String”作为dataType,但这些都没有工作。requireddataType

是我错过了什么,还是这只是swagger-spring-mvc库中的一个错误?


答案 1

事实证明,这在当前版本的Swagger Spring MVC库中完全被忽略了。我在这里找到了一个关于它的简短讨论:dataType

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

看起来一旦发布,它就可以包含在版本2中。

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

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

答案 2

对于OpenApi(Swagger 3.0)和SpringDoc,可以使用以下全局配置。

static {
     SpringDocUtils.getConfig().replaceWithSchema(Money.class, new StringSchema());
}

推荐