❤️java jackson全局设置LocalDateTime的格式

小明的学习圈子2023-09-20后端日期

在之前jackson设置Date类型的格式时,只需要在springboot的配置文件里面加上以下配置即可:

spring:
  jackson:
    default-property-inclusion: non_null # 不处理空值
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

但是当处理LocalDateTime的时候,这种全局配置就失效了。当将json字符串反序列化为java对象时,也会出现反序列化的错误,因为LocalDateTime默认的格式为yyyy-MM-ddTHH:mm:ss,中间带了个T,如果json字符串中不是按照这个格式的话就会报错。

解决方法:

1、给每一个LocalDateTime就加上@JsonFormat注解

    @ApiModelProperty("创建时间")
    @TableField(fill = FieldFill.INSERT)
    //@JsonFormat( pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private LocalDateTime gmtCreate;

2、全局配置类

package com.stu.myserver.config;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
@ConditionalOnClass(JavaTimeModule.class)
public class JavaTimeAutoConfiguration {

    @Bean
    @ConditionalOnProperty("spring.jackson.date-format")
    Jackson2ObjectMapperBuilderCustomizer customizeLocalDateTimeFormat(@Value("${spring.jackson.date-format}") String dateFormat){
        return jacksonObjectMapperBuilder -> {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);

            jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
            jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        };
    }
}


Last Updated 2024/4/6 11:55:17