我使用的是Jackson 2.8,需要与不允许在ISO 8601时间戳内持续几毫秒的API进行通信。Jackson,java.time,ISO 8601,无序列化
预期的格式是这样的:"2016-12-24T00:00:00Z"
我使用的是杰克逊的JavaTimeModule与WRITE_DATES_AS_TIMESTAMPS
设置为false
。
但是这会打印毫秒。
所以我试图用objectMapper.setDateFormat
哪些没有改变任何东西。
我目前的解决方法是这样的:
ObjectMapper om = new ObjectMapper();
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendInstant(0)
.toFormatter();
JavaTimeModule jtm = new JavaTimeModule();
jtm.addSerializer(Instant.class, new JsonSerializer<Instant>() {
@Override
public void serialize(Instant value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
gen.writeString(dtf.format(value));
}
});
om.registerModule(jtm);
我重写了Instant.class
其运作默认的序列。
有没有什么好的方法使用一些配置参数来解决这个问题?
你试过'DateTimeFormatter.ISO_INSTANT'作为格式吗? https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_INSTANT – Gelunox
目标API超出了你的控制范围? –
是的,试过了。它也会打印毫秒。如果我明确创建一个毫秒设置为“0”的“即时”,也许它可以工作。但这对我的用例来说不够安全。它必须**总是**忽略/丢弃串行化的毫秒数。 '......编辑:'是的,API来自外部公司。无控制。 –