Jackson序列化LocalDate与Springboot集成

前言

Java8的date API一经推出便广受好评,今日也准备用一用,然后就用出问题了。基本用法见https://www.cnblogs.com/woshimrf/p/java8-date-api.html

问题

LocalDate可以很友好的toString为YYYY-MM-dd的格式,很适合我当前的业务,但当我把它丢到json的时候,瞬间解体了:

{
  "year": 2018,
  "month": "AUGUST",
  "era": "CE",
  "dayOfMonth": 1,
  "dayOfWeek": "TUESDAY",
  "dayOfYear": 213,
  "leapYear": false,
  "monthValue": 8,
  "chronology": {
      "id":"ISO",
      "calendarType":"iso8601"
   }
}

可我想要的是yyyy-MM-dd啊。加上jackson format试一试,也不行。

@JsonFormat(shape = JsonFormat.Shape.STRING,
        pattern = "yyyy-MM-dd", timezone = "Asia/Shanghai")

难道要手动实现JsonSerializer? google之,果然有人解决了。

解决

添加

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
  <version>2.8.6</version>
</dependency>

用法

@Test
public void testJsonFormat() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    LocalDate date = LocalDate.of(2018, 5, 5);
    String dateStr = mapper.writeValueAsString(date);
    Assert.assertEquals("\"2018-05-05\"", dateStr);

    LocalDateTime dateTime = LocalDateTime.of(2018, 5, 5, 1, 1, 1);
    Assert.assertEquals("\"2018-05-05T01:01:01\"", mapper.writeValueAsString(dateTime));
}

然而,在Springboot中,默认提供了ObjectMapper,我又不想自定义。

Springboot中使用

同样把上述jar加入依赖。然后修改配置文件,新增

spring:
  jackson:
    serialization:
      WRITE_DATES_AS_TIMESTAMPS: false

这样可以直接使用LocalDate,不用单独JsonFormat就可以实现自己的功能了。

LocalDateTime序列化

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

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

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

}

参考

原文连接:https://reflectoring.io/configuring-localdate-serialization-spring-boot/ 作者: Tom Hombergs

posted @ 2018-05-30 08:43  Ryan.Miao  阅读(10676)  评论(2编辑  收藏  举报