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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With