Force Milliseconds When Serializing Instant to ISO8601 using Jackson

前端 未结 5 623
野的像风
野的像风 2021-01-11 15:01

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.R

5条回答
  •  轮回少年
    2021-01-11 15:16

    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

提交回复
热议问题