ZonedDateTime使用FasterXML Jackson序列化纪元毫秒

时间:2017-05-02 05:51:27

标签: java java-8 jackson fasterxml zoneddatetime

我打算使用纪元毫秒进行反序列化和序列化。 但是,只有反序列化有效但无法序列化回到正确的ZonedDateTime

ObjectMapper mapper = new ObjectMapper();
mapper.setTimeZone(TimeZone.getDefault());
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);

System.out.println(mapper.writeValueAsString(ZonedDateTime.now()));  // print 1493703996728 [Expected]
System.out.println(mapper.readValue("1493703996728", ZonedDateTime.class)); // print +49303-08-07T00:52:08+08:00[Asia/Singapore] [Unexpected]

如何使序列化获取2017-05-02T13:46:36.728+08:00[Asia/Singapore]的日期?

版本的com.fasterxml.jackson。*都是2.8.8

1 个答案:

答案 0 :(得分:3)

您还需要禁用反序列化的纳秒来使Jackson解析毫秒:

mapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);