Java 8 DateTime support error


What's inside this article ⌄
  • Java 8 datetime not supported
  • Java time type error fix
  • Java 8 date support missing
  • Java datetime compatibility error

Suppose we want to serialize some object to JSON. We 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)

First, let’s add a dependency from mvn repo.

For Maven:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.14.2</version>
</dependency>

For Gradle:

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’re 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, check this link.