Java 8 date/time type not supported

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:

  1. Add jackson-datatype-jsr310 dependency to our application
  2. Register JavaTimeModule within ObjectMapper (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 Optional
  • jackson-datatype-jsr310: support for Java 8 Date and Time API types
  • jackson-datatype-joda: support for Joda-Time types
  • jackson-module-kotlin: support for Kotlin classes and data classes

For additional info: https://www.baeldung.com/spring-boot-customize-jackson-objectmapper.

Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.

If I saved your day, you can support me 🤝

Leave a Reply

Your email address will not be published. Required fields are marked *