一、背景说明

在使用SpringBoot+SpringMVC时,默认采用Jackson包来进行JSON转换。

在返回Date类型的数据时,Jackson会以时间戳的形式返回,而实际场景往往需要以yyyy-MM-dd HH:mm:ss这类日期或时间格式返回。

二、解决方案

有几种方式可以对Date格式进行设置:

  1. 在application.properties中做全局配置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.serialization.write-dates-as-timestamps=false

这种方式只对 date 类型生效

  1. 在单个实体类的属性上面使用@JsonFormat注解

如果你的Date类型要返回一个非yyyy-MM-dd HH:mm:ss格式的信息,则需要使用@JsonFormat注解:

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date createTime;
  1. 采用@JsonComponent注解,来实现JsonSerializer和JsonDeserializer

使用 @JsonFormat 注解并不能完全做到全局时间格式化,所以接下来我们使用 @JsonComponent 注解自定义一个全局格式化类,分别对 DateLocalDate 类型做格式化处理。

@JsonComponent
public class DateFormatConfig {

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

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilder() {
        return builder -> {
            TimeZone tz = TimeZone.getTimeZone("UTC");
            DateFormat df = new SimpleDateFormat(pattern);
            df.setTimeZone(tz);
            builder.failOnEmptyBeans(false)
                    .failOnUnknownProperties(false)
                    .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                    .dateFormat(df);
        };
    }

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

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

全局配置之后对于某些字段不希望使用这样的格式,则对此字段额外设置@JsonFormat即可,这个注解的优先级更高