[英]How to set @ApiModelProperty dataType to String for Swagger documentation
我正在使用 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 注释放在字段和方法上,并且在这两种情况下都尊重required
字段,但忽略了dataType
字段。 我也试过对 dataType 使用“String”、“string”和“java.lang.String”,但这些都没有奏效。
我是否遗漏了什么,或者这只是 swagger-spring-mvc 库中的一个错误?
事实证明,在当前版本的 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);
}
对于 OpenApi (Swagger 3.0) 和 SpringDoc,可以使用以下全局配置。
static {
SpringDocUtils.getConfig().replaceWithSchema(Money.class, new StringSchema());
}
@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.