Jackson Serialize Instant to Nanosecond Issue

后端 未结 2 1691
予麋鹿
予麋鹿 2020-11-28 16:01

Jackson serialises java.time.Instant with WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS enabled by default.

It produces JSON

2条回答
  •  难免孤独
    2020-11-28 16:56

    I took Michal's idea above and wrapped the existing com.fasterxml.jackson.datatype.jsr310.DecimalUtils#toBigDecimal(long seconds, int nanoseconds) in a serializer

    class ShortInstantSerializer extends StdSerializer {
        ShortInstantSerializer() {
            super(Instant.class);
        }
    
        @Override
        public void serialize(Instant value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            gen.writeNumber(DecimalUtils.toBigDecimal(value.getEpochSecond(), value.getNano()));
        }
    }
    

    Also, if you're going to be reading it back at some point, the value will be deserialized into a Double. To go back do this (thanks inverwebs!)

    public static Instant toInstant(Double d) {
        long seconds = d.longValue();
        long micros = Math.round((d - seconds) * 1_000_000);
        return Instant.ofEpochSecond(seconds).plus(micros , ChronoUnit.MICROS);
    }
    

提交回复
热议问题