Learn about fixing the error "Java 8 date/time type `java.time.Instant` not supported by default" when serializing and deserializing Java 8 date-time classes using Jackson.
1. Questions
Errors occur when we serialize Java objects or deserialize JSON into POJOs, and POJOs contain new Java 8 datetime classes like LocalDate, LocalTime, LocalDateTime, etc.
For example, the Employee class below has a field of type LocalDate.
public class Employee {
private Long id;
private String name;
private LocalDate dateOfBirth;
}
When we serialize an instance of this class, we get the following exception:
Exception in thread "main" java.lang.IllegalArgumentException: Java 8 date/time type `java.time.LocalDate` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.howtodoinjava.core.objectToMap.Employee["dateOfBirth"])
at com.fasterxml.jackson.databind.ObjectMapper ._convert(ObjectMapper.java:4393)
at com.fasterxml.jackson.databind.ObjectMapper .convertValue(ObjectMapper.java:4324)
at com.howtodoinjava.core.objectToMap .ObjectToMapUsingJackson.main(ObjectToMapUsingJackson.java:25)
An example of exception,
When you visit the /actuator/info node, you will find the following error page
This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.
2. Solutions
We had to add support for new Java 8 classes in two steps to fix this bug.
First, add the latest version of the com.fasterxml.jackson.datatype:jackson-datatype-jsr310 Maven dependency.
pom.xml
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.4</version>
</dependency>
Second, depending on what you use, register the module JavaTimeModule with ObjectMapper or JsonMapper.
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
//or
JsonMapper jsonMapper = new JsonMapper();
jsonMapper.registerModule(new JavaTimeModule());