Jackson序列化和反序列化LocalDatetime

Stars-one 2021年05月09日 55次浏览 本篇字数为914字

本文为作者原创,转载请注明出处,谢谢配合
作者:Stars-one
链接:https://stars-one.site/2021/05/09/jackson-format-localdatetime


在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
}