2,268 total views, 12 views today
Swagger UI 的页面中,请求的数据类型会被序列化成字符串,显示在 Model Schema 中。
但是,Java8 中的 LocalDateTime 类型会被序列化成很复杂的字符串,如下图。

解决的办法其实很简单,在 Swagger 的配置中,添加 directModelSubstitute 方法的代码
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的优化/
|