Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: Default serialization for java.time.Duration changed from String to Number

We upgraded lately from Spring Boot 2.1.9 to 2.2.1 which caused our tests to fail. Investigation led to the result that the java.time.Duration type is now serialized differently by default. Instead of having the String "PT15M" in the JSON message we now get "900.0". The POJO definition looks like that

@JsonProperty(required = true, value = "duration")
@NotNull
private final Duration duration;

The question now is if there is some configuration property we can use to get the "old" behavior. I know we could also add annotation

@JsonFormat(shape = JsonFormat.Shape.STRING)

but I would prefer a way to have it just by configuration.

like image 540
hecko84 Avatar asked Nov 12 '19 08:11

hecko84


People also ask

How to set default date format in Spring Boot with JSON?

If we want to configure a default format for all dates in our application, a more flexible way is to configure it in application.properties: spring.jackson.date-format=yyyy-MM-dd HH:mm:ss. And if we want to use a specific time zone in our JSON dates, there's also a property for that: spring.jackson.time-zone=Europe/Zagreb.

What is the default way of serialization in Java?

Java specifies a default way in which objects can be serialized. Java classes can override this default behavior. Custom serialization can be particularly useful when trying to serialize an object that has some unserializable attributes.

What is the default version of Spring Boot for starter web?

This tutorial is based on Spring Boot version 1.3.1.RELEASE with spring-boot-starter-web. It uses jackson-datatype-jsr310 from com.fasterxml.jackson.datatype in version 2.6.4, which is a default version of Spring Boot.

How to set default time zone in JSON dates in spring Jackson?

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss. And if we want to use a specific time zone in our JSON dates, there's also a property for that: spring.jackson.time-zone=Europe/Zagreb. Although setting the default format like this is quite handy and straightforward, there's a drawback to this approach.


1 Answers

When you changed the version of spring-boot from 2.1.9 to 2.2.1 , there is also a change of version for the Jackson. From Spring-boot version 2.2 onwards the Jackson version is changed to 2.10. One of the changes that are part of this Jackson version change is the use of the flag SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS for serializing the Duration time stamps instead of the earlier WRITE_DATES_AS_TIMESTAMPS.

By adding following property to the application.properties the service (and the serialization feature) will behave like pre 2.2

spring.jackson.serialization.write-durations-as-timestamps=false

Springboot 2.2 Changelist

Jackson 2.10 changelist

Jackson Issue tracker

like image 180
Ananthapadmanabhan Avatar answered Oct 29 '22 14:10

Ananthapadmanabhan