Nasibulloh Yandashev
Nasibulloh Yandashev

Reputation: 591

Spring Boot Jackson does not serialize timestamps in Long

I'm using Spring boot 2.3.1 version in my project. JDK version 11. I used Instant to return date. But I wanted to return date in Long, not in text format. That's why I configured Jackson. But, Spring Boot generates timestamps in double instead of long. I configured Jackson in application.yml file with

jackson:
date-format: com.fasterxml.jackson.databind.util.ISO8601DateFormat
serialization:
  write-dates-as-timestamps: on
deserialization:
  read_date_timestamps_as_nanoseconds: on
time-zone: 'UTC'

But when receive timestamps in nanos they are not in Long type, They are in Double like=1593679103.899854000

How can be fixed it?

Upvotes: 0

Views: 902

Answers (1)

Nasibulloh Yandashev
Nasibulloh Yandashev

Reputation: 591

Spring's Jackson converts types by default. In order to change type, conversions need to override the default configuration. The question above can be fixed by the following configuration.

@Bean
public JavaTimeModule javaTimeModule() {
var javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(Instant.class, new InstantToLongSerializer());
return javaTimeModule;
}

static class InstantToLongSerializer extends JsonSerializer<Instant> {

@Override
public void serialize(Instant value, JsonGenerator gen, SerializerProvider serializers)
    throws IOException {
  gen.writeNumber(value.toEpochMilli());
}
}

Upvotes: 0

Related Questions