分享

Swagger序列化LocalDateTime的优化

 wwq图书世界 2019-11-19

Swagger 序列化 LocalDateTime 的优化

wusq Java基础 六月 20, 2019

2,268 total views, 12 views today

Swagger UI 的页面中,请求的数据类型会被序列化成字符串,显示在 Model Schema 中。

但是,Java8 中的 LocalDateTime 类型会被序列化成很复杂的字符串,如下图。

解决的办法其实很简单,在 Swagger 的配置中,添加 directModelSubstitute 方法的代码

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.directModelSubstitute(LocalDateTime.class, Date.class)
.directModelSubstitute(LocalDate.class, String.class)
.directModelSubstitute(LocalTime.class, String.class)
.directModelSubstitute(ZonedDateTime.class, String.class)
.apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.abcd.restful")).paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Platform API").contact("abcd").version("1.0").build();
}
}

directModelSubstitute 方法顾名思义就是在序列化的时候用一个类型代替一个类型。

上面的例子,LocalDateTime 类型用 Date 类型替代,LocalDate 类型直接用 String 类型替代,这样就避免的 Swagger 原生的序列化方法把 LocalDateTime 序列化的很复杂。效果如下:

原创文章,转载请注明出处!http://www./swagger序列化localdatetime的优化/

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多