Spring Boot应用程序中Swagger2和jackson-datatype-jsr310之间的冲突



我正在使用Spring Boot创建一个REST API,并且在使用Swagger 2时出现了串行化LocalDateTime的问题。

如果没有Swagger,JSON输出如下:

{
"id": 1,
...
"creationTimestamp": "2018-08-01T15:39:09.819"
}

Swagger是这样的:

{
"id": 1,
...
"creationTimestamp": [
2018,
8,
1,
15,
40,
59,
438000000
]
}

我已经将此添加到pom文件中,以便正确序列化日期:

<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

这是Jackson的配置:

@Configuration
public class JacksonConfiguration {
@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}

这就是Swagger:的配置

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebMvcConfigurationSupport {
@Bean
public Docket messageApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxx.message.controller"))
.build()
.apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("Message service")
.version("1.0.0")
.build();
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}

当我像这样向DTO的字段添加一个取消序列化程序时,它就起作用了。然而,它应该在不需要添加它的情况下工作。

@JsonFormat(pattern = "dd/MM/yyyy")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime creationTimestamp;

我想问题是Swagger有自己的对象映射器,它覆盖了另一个。你知道怎么解决吗?

提前感谢

正如我所看到的,问题发生在SwaggerConfiguration扩展WebMvcConfigurationSupport时。如果你不需要,你可以删除这个扩展。

最新更新