我在一个项目中使用 Spring Boot 2.0.0.M6
、Spring Framework 5.0.1 时有一些关于使用 Jackson 进行 JSON 序列化 的问题。发布
和 Jackson 2.9.2
。
我在 application.properties
中配置了以下与 Jackson 相关的设置:
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
序列化主要在我需要的时候工作。不过,我注意到 Jackson 似乎会在 000
时截断毫秒数。
测试 1:将毫秒设置为 000
的 Instant 序列化:
- 使用
Instant.parse("2017-09-14T04:28:48.000Z")
初始化 Instant 字段 - 使用 Jackson 序列化它
- 输出将为
"2017-09-14T04:28:48Z"
测试 2:将毫秒设置为某个非 000
值的 Instant 序列化:
- 使用
Instant.parse("2017-09-14T04:28:48.100Z")
初始化 Instant 字段 - 使用 Jackson 序列化它
- 输出将为
"2017-09-14T04:28:48.100Z"
问题:
- 这是设计使然的行为吗?
- 我能做些什么来强制序列化
000
吗?
最佳答案
我用这个方法解决了:
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
module.addSerializer(Instant.class, new InstantSerializerWithMilliSecondPrecision());
objectMapper.registerModule(module);
对于 InstantSerializerWithMilliSecondPrecision 我使用了这个:
public class InstantSerializerWithMilliSecondPrecision extends InstantSerializer {
public InstantSerializerWithMilliSecondPrecision() {
super(InstantSerializer.INSTANCE, false, new DateTimeFormatterBuilder().appendInstant(3).toFormatter());
}
}
现在即时序列化总是包含毫秒。示例:2019-09-27T02:59:59.000Z
关于java - 使用 Jackson 将 Instant 序列化为 ISO8601 时强制毫秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47502158/