SpringBoot系列之自定义Jackson对象映射器格式日期数据

2023-11-03 08:25:10 浏览数 (1)

开发环境

  • JDK 1.8
  • SpringBoot2.2.1
  • Maven 3.2
  • Mysql5.7.36
  • 开发工具
    • IntelliJ IDEA
    • smartGit

背景

在我之前的博客中,有对Springboot2.0集成Mybatis Plus做了比较详细的描述,现在这篇博客介绍,基于开源的jackson api来自定义ObjectMapping(对象映射器),实现对实体类中的日期数据,统一格式化处理

问题描述

我们定义一个实体类

代码语言:javascript复制
@Data
public class UserDO {
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    
    private String name;
    
    private Integer age;
    
    private String email;

    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime modifyTime;
    
}

通过mybatisplus统一写好接口,返回,这个LocalDateTime的日期都是如图所示这样的,所以都需要手工格式化处理

解决方案

在jackson中,可以通过自定义ObjectMapping实现对日期格式的数据统一处理,通过Jackson2ObjectMapperBuilderCustomizer统一对LocalDateLocalDateTime做格式化处理

代码语言:javascript复制
package com.example.mybatisplus.configuration;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.mybatis.spring.annotation.MapperScan;
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.format.DateTimeFormatter;

@Configuration
@MapperScan("com.example.mybatisplus.mapper")
public class MybatisPlusConfiguration {

    private static final String dateFormat = "yyyy-MM-dd";

    private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";

    @Bean
    @ConditionalOnProperty(value = "spring.jackson.date-format", matchIfMissing = true, havingValue = "none")
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> builder.serializationInclusion(JsonInclude.Include.NON_NULL)
                .simpleDateFormat(dateTimeFormat)
                .serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)))
                .serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
    }

}

0 人点赞