在Spring Boot项目中,由于使用了JDK8推荐使用的LocalDateTime类,但是在传回给前端的json却没有正确的格式化,于是有了下面的解决方法
解决方法
1.导入依赖
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.7</version>
</dependency>
2.注入bean
@Bean
fun serializingObjectMapper(): ObjectMapper {
//localdatetime的序列化和反序列化
val module = JavaTimeModule()
val localDateTimeSerializer = LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern))
val localDateTimeDeserializer = LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern))
module.addDeserializer(LocalDateTime::class.java, localDateTimeDeserializer)
module.addSerializer(LocalDateTime::class.java, localDateTimeSerializer)
val objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(module,KtormModule())
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build<ObjectMapper>()
return objectMapper
}
评论区