Spring Boot: LocalDateTime not parsing to JSON correctly
When creating a Spring Boot Rest service, you can configure Spring to convert a LocalDateTime to display as a ISO-8601 date string when returning a JSON response.
To get this working you have to do a few things.
Firstly, you need the following dependency: com.fasterxml.jackson.datatype:jackson-datatype-jsr310
This dependency has all the JSON serialisers and deserialisers for the Java 8 time API, and when you use Spring Boot with auto configuration, it should load all the correct serialisers. Secondly, you need to add the following to your application properties:
spring:
jackson:
serialization:
WRITE_DATES_AS_TIMESTAMPS: false
This makes sure that none of the dates are parsed to a timestamp, and it will now parse to the default textual representation, which is the ISO-8601 standard. The expected result date would look like this “2018-11-01T16:24:59.915469” in your JSON response of your API.
Hmmmmmm why wasn’t this working for us?
In our case, this wasn’t working for some reason, because we got the dates like this:
[
2018,
11,
1,
16,
32,
53,
538873000
]
After debugging for hours, we found some old code that had the Spring annotation @EnableWebMvc. When we removed this everything was working as expected. Apparently, the Spring Boot web MVC auto configuration is disabled when adding the annotation @EnableWebMvc, so the serializers from the dependency weren’t loaded correctly.
In the end it was a simple fix. Although the Spring guide mentions that the @EnableWebMvc isn’t needed, it does not mention it will potentially break things: “Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.”.