我使用的是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來自外部公司。無控制。 –