LocalDateTime的json自定义格式化问题

创建json格式化配置文件

package com.atguigu.srb.base.config;

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 java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class LocalDateTimeSerializerConfig {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}

上面的方案全局生效,当全局的格式化方式无法满足我们需求时,我们对日期格式要做特殊的处理:在类的属性上添加注解 

@JsonFormat(pattern = "yyyy-MM-dd")
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;

单独做个性化处理 

 

你可能感兴趣的:(小工具库,json,java,spring)