Spring Boot Jackson Date and Timestamp Format

Is Default serialization format of Date has changed with recent Spring boot versions/Jackson Versions?

It comes from jackson-databind 2.11.0.(diff)

  • Spring Boot 2.2.0: 2.10.0
  • Spring Boot 2.2.8: 2.10.4
  • Spring Boot 2.3.0: 2.11.0

so, it seems this behavior is Spring Boot 2.3.0 or later.

Spring Boot Jackson does not serialize timestamps in Long

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());
}
}

Jackson change timestamp format

I want to change the java.sql.Timestamp format globally.

Set a date format to your ObjectMapper instance:

ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"));

In Spring applications, you can expose the ObjectMapper instance as a bean:

@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"));
return mapper;
}

In Spring Boot you can use the property spring.jackson.date-format to define the date format:

spring.jackson.date-format: yyyy-MM-dd HH:mm:ss.S

For more details on the common application properties, refer to the documentation.


Consider the following code:

Map<String, Object> data = new HashMap<>();
data.put("date", new Timestamp(ZonedDateTime.now().toInstant().toEpochMilli()));
System.out.println(mapper.writeValueAsString(data));

It will print:

{"date":"2018-04-26 07:25:14.408"}


Related Topics



Leave a reply



Submit