我有swagger 2.8.0,我的 POJO 类如下,
public class Item {
@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate date;
@JsonFormat(pattern="HH:mm")
private LocalTime time;
// other fields and Getters and Setters are omitted for brevity
}
现在在 swagger-ui 的示例值部分中,我的 POJO 模型显示为
{
"date": "string",
"time": {
"hour": 0,
"minute": 0,
"nano": 0,
"second": 0
}
}
如何在 swagger-ui 中将 LocalTime 显示为字符串?
在 swagger 配置中试试这个
directModelSubstitute将解决这个问题
@Bean
public Docket postsApi() {
return new Docket(DocumentationType.SWAGGER_2)//.groupName("public-api")
.groupName("")
.directModelSubstitute(LocalDateTime.class, String.class)
.directModelSubstitute(LocalDate.class, String.class)
.directModelSubstitute(LocalTime.class, String.class)
.directModelSubstitute(ZonedDateTime.class, String.class)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.paths(PathSelectors.any())
.paths(postPaths()).build().useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET, getCustomizedResponseMessages());
}
对于 springdoc-openapi-starter-webmvc-ui 您可以添加 Schema 注释
@Schema(type = "String", pattern = "HH:mm:SS")
LocalTime localTime
有一个未记录的静态 public 方法,称为 PrimitiveType.enablePartialTime()。当您在加载上下文阶段运行此方法时,它会将
java.util.LocalTime
添加到原始类型列表中,并将其转换为具有 string
格式的 partial-time
类型。
我需要在 XML 定义中使用它,因此我使用了以下配置:
<bean name="localTimeFixer" class="io.swagger.v3.core.util.PrimitiveType" factory-method="enablePartialTime"/>
但是,在 annotated 或 Spring Boot 上下文中,它甚至更简单,因为您可以直接在初始化 bean 中调用此方法。
PrimitiveType.enablePartialTime()
自版本
2.0.6
以来,它就在库中,其中修复了问题。
在这里找到了这样的解决方案。
import io.swagger.v3.oas.models.media.Schema;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import org.springdoc.core.utils.SpringDocUtils;
static {
var schema = new Schema<LocalTime>();
schema.example(LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
SpringDocUtils.getConfig().replaceWithSchema(LocalTime.class, schema);
}