自定义spring对LocalDateTime的序列化/反序列化方式

spring支持自定义各种类型的JsonSerializer/JsonDeserializer,配置方式很简单,如下:


import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer
import java.time.format.DateTimeFormatterBuilder

@Configuration
class ApplicationConfig {
    @Bean
    fun jackson2ObjectMapperBuilderCustomizer(): Jackson2ObjectMapperBuilderCustomizer {
        return Jackson2ObjectMapperBuilderCustomizer { builder ->
            // 序列化用的是jackson的LocalDateTimeSerializer(也可以自己实现)
            builder.serializers(
                LocalDateTimeSerializer(
                    DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd HH:mm:ss")
                        .appendLiteral('这个方法直接追加文本')
                        .toFormatter(Locale.CHINESE)
                )
            )
			// 反序列化用了自己实现的(也可以用各种现成的)
            builder.deserializers(LocalDateTimeDeSerializer())
        }
    }
}

反序列化的LocalDateTimeDeSerializer实现例子:


import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fina.summer.chargeplan.extension.beijingZone
import java.time.LocalDateTime

/**
 * @description 将毫秒时间戳反序列化成LocalDateTime
 */

class LocalDateTimeDeSerializer : JsonDeserializer<LocalDateTime>() {
    override fun deserialize(jsonParser: JsonParser?, p1: DeserializationContext?): LocalDateTime {
        jsonParser?.text?.toLong()!!.let {
            return LocalDateTime.ofEpochSecond(it.div(1000), it.rem(1000).toInt(), 
ZoneOffset.of("+8"))
        }
    }
}

Date类也差不多啦,现在比较推荐LocalDateTime,所以就用这个举例啦。还有这个是kotlin的写法,java也差不多啦

你可能感兴趣的:(Spring,实用代码片段)