Serialize LocalDate and LocalDateTime as Unix timestamps

那年仲夏 提交于 2019-12-05 13:52:49

In the JavaDoc to JavaTimeModule (included in jackson-datatype-jsr310 library), we can read the following:

Most java.time types are serialized as numbers (integers or decimals as appropriate) if the SerializationFeature.WRITE_DATES_AS_TIMESTAMPS feature is enabled [...]

[...] If SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS is disabled, timestamps are written as a whole number of milliseconds. [...]

and then:

Some exceptions to this standard serialization/deserialization rule:

  • [...]
  • LocalDate, LocalTime, LocalDateTime, and OffsetTime, which cannot portably be converted to timestamps and are instead represented as arrays when WRITE_DATES_AS_TIMESTAMPS is enabled.

You can indeed see that LocalDateTime cannot be ubiquitously converted to the Unix timestamp because its toEpochSecond method takes ZoneOffset as parameter.

To sum up, it seems the best thing you can do is replacing LocalDateTime with Instant (see this great answer for an explanation of the difference between LocalDateTime and Instant).

Other than that, you would indeed need custom JsonSerializer and JsonDeserializer.


Here's a working code sample:

public static void main(String[] args) throws Exception {
    ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);

    Entity entity = new Entity(Instant.now());

    StringWriter writer = new StringWriter();
    objectMapper.writeValue(writer, entity);
    System.out.println(writer.getBuffer());
}

@lombok.Value
static class Entity {
    Instant timestamp;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!