Spring Boot Jackson序列化 Java8 LocalDate(Kotlin版)

1,214 阅读1分钟

如果没有做转化的话,返回给前端的时间见将会是带T的ISO标准的时间。对于中国的本土化并不是很适合。

如下图

由于Java8中可以使用了新的LocalDate/LocalDateTime函数获取本地时间。 所以导致在application.yml中jason的date-format配置无效,因为配置文件是针对的Java Date。

  jackson:
    date-format: "yyyy-MM-dd HH:mm:ss"

使用下面的@Configuration配置文件后即可转为为我们常见的yyyy-MM-dd HH:mm:ss格式的时间返回给前端。

package com.demo.configuration

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter


@Configuration
class LocalDateTimeSerializerConfig {
    @Value("\${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private val pattern: String? = null

    @Bean
    fun localDateTimeDeserializer(): LocalDateTimeSerializer? {
        return LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern))
    }

    @Bean
    fun jackson2ObjectMapperBuilderCustomizer(): Jackson2ObjectMapperBuilderCustomizer? {
        return Jackson2ObjectMapperBuilderCustomizer { builder: Jackson2ObjectMapperBuilder ->
            builder.serializerByType(
                LocalDateTime::class.java, localDateTimeDeserializer()!!
            )
        }
    }
}

代码参考可以clone这个

参考原文Jackson序列化LocalDate与Springboot集成