我在 Spring Boot 应用程序中使用 Java 8 DateTime 和 Jackson jsr 310 支持。
我禁用 了SerializationFeature.WRITE_DATES_AS_TIMESTAMPS以强制杰克逊将 localDatetime 序列化为字符串而不是 int 数组。
但是当日期时间微秒或非秒为0结尾时,我发现了一个奇怪的格式问题。我认为序列化结果可能等于date.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),但事实并非如此,格式方法省略了零。
完整的示例测试代码。
private LocalDateTime date;
private OffsetDateTime offsetDate;
private ZonedDateTime zonedDate;
@Before
public void setup() throws ServletException {
date = LocalDateTime.of(2015, 8, 15, 11, 40, 10, 100_000_000);
offsetDate = OffsetDateTime.of(2015, 8, 15, 11, 40, 10, 100_000_000, ZoneOffset.ofHours(8));
zonedDate = ZonedDateTime.of(2015, 8, 15, 11, 40, 10, 100_000_000, ZoneId.of("Asia/Shanghai"));
}
@Test
public void testDateFormat() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("localDate", date);
map.put("offsetDate", offsetDate);
map.put("zonedDate", zonedDate);
String json = objectMapper.writeValueAsString(map);
log.debug("converted json result @" + json);
JsonNode rootNode = objectMapper.readTree(json);
JsonNode localDateNode = rootNode.get("localDate");
assertEquals("local date should be equals", date.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME), localDateNode.textValue());
JsonNode offsetDateNode = rootNode.get("offsetDate");
assertEquals("offsetDate date should be equals", offsetDate.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME), offsetDateNode.textValue());
JsonNode zonedDateNode = rootNode.get("zonedDate");
assertEquals("zonedDate date should be equals", zonedDate.format(DateTimeFormatter.ISO_ZONED_DATE_TIME), zonedDateNode.textValue());
}
测试失败,日志调试打印
{
"zonedDate":"2015-08-15T11:40:10.100+08:00[Asia/Shanghai]",
"localDate":"2015-08-15T11:40:10.100",
"offsetDate":"2015-08-15T11:40:10.1+08:00"
}
zonedDate和localDate微秒以00结尾,但 offsetDate 不是。并且date.format也得到不同的结果,其中 micrseconds不以00结尾。
format、toString、json文本的打印结果
LocalDateTime format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)@2015-08-15T11:40:10.1
LocalDateTime toString @2015-08-15T11:40:10.100
LocalDateTime serialized json node text @2015-08-15T11:40:10.100
OffsetDateTime format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)@2015-08-15T11:40:10.1+08:00
OffsetDateTime toString @2015-08-15T11:40:10.100+08:00
OffsetDateTime serialized json node text @2015-08-15T11:40:10.1+08:00
ZonedDateTime format(DateTimeFormatter.ISO_ZONED_DATE_TIME)@2015-08-15T11:40:10.1+08:00[Asia/Shanghai]
ZonedDateTime toString @2015-08-15T11:40:10.100+08:00[Asia/Shanghai]
ZonedDateTime serialized json node text @2015-08-15T11:40:10.100+08:00[Asia/Shanghai]
- 似乎toString结果应该是 Jackson 序列化中的期望结果,在上面的日志记录中,OffsetDateTime json 节点微秒文本应该以00结尾。
- 为什么格式方法结果省略了结尾00?
完整的示例代码可以从我的 github.com 找到。