I have some questions related to JSON serialization using Jackson in a project where I use Spring Boot 2.0.0.M6
, Spring Framework 5.0.1.RELEASE
and Jackson 2.9.2
.
I have configured the following Jackson-related settings in application.properties
:
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
Serialization works mostly as I need. Nevertheless, I have noticed that Jackson seems to cut-off milliseconds if they are 000
.
Test 1: Serialize Instant with milliseconds set to 000
:
Instant.parse("2017-09-14T04:28:48.000Z")
"2017-09-14T04:28:48Z"
Test 2: Serialize Instant with milliseconds set to some non-000
value:
Instant.parse("2017-09-14T04:28:48.100Z")
"2017-09-14T04:28:48.100Z"
Questions:
000
?I solve using this aproach:
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
module.addSerializer(Instant.class, new InstantSerializerWithMilliSecondPrecision());
objectMapper.registerModule(module);
And for InstantSerializerWithMilliSecondPrecision i used this:
public class InstantSerializerWithMilliSecondPrecision extends InstantSerializer {
public InstantSerializerWithMilliSecondPrecision() {
super(InstantSerializer.INSTANCE, false, new DateTimeFormatterBuilder().appendInstant(3).toFormatter());
}
}
Now the Instant serialization always includes milliseconds. Example: 2019-09-27T02:59:59.000Z