Suppose you want to serialize some object to JSON. You may encounter the exception:
Java 8 date/time type `java.time.Instant` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling
We need to do two steps:
- Add
jackson-datatype-jsr310
dependency to our application - Register
JavaTimeModule
withinObjectMapper
(see this section in details).
Firstly, let’s add dependency from https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310.
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.14.2</version>
</dependency>
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.2'
Next, let’s register JavaTimeModule
within ObjectMapper
:
ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
If you working with Spring or with some other framework, ObjectMapper can be instantiated implicitly. You need to override instantiation by yourself.
For Spring, you merely need to define bean of type ObjectMapper:
@Bean
@Primary
public ObjectMapper objectMapper() {
JavaTimeModule module = new JavaTimeModule();
return new ObjectMapper().registerModule(module);
}
Also, there are modules for other classes:
jackson-datatype-jdk8
: support for other Java 8 types like Optionaljackson-datatype-jsr310
: support for Java 8 Date and Time API typesjackson-datatype-joda
: support for Joda-Time typesjackson-module-kotlin
: support for Kotlin classes and data classes
For additional info: https://www.baeldung.com/spring-boot-customize-jackson-objectmapper.
If you still have any questions, feel free to ask me in the comments under this article, or write me on promark33@gmail.com.