How to handle Java 8 date/time type java.time.LocalDateTime not supported exception

March 27, 2022 No comments Java LocalDateTime Java8

1. Introduction

In this short article, we will present a solution for the Java 8 date/time type java.time.LocalDateTime not supported by default exception. This kind of exception is thrown when we tried to convert an Object with LocalDateTime from Java 8 using ObjectMapper.

2. The java.lang.IllegalArgumentException: Java 8 date/time type java.time.LocalDateTime not supported by default

When you face that kind of a warning your console log will probably have the following stack trace.

java.lang.IllegalArgumentException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.frontbackend.model["created"])
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:4393) ~[jackson-databind-2.13.1.jar:2.13.1]
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:4334) ~[jackson-databind-2.13.1.jar:2.13.1]

3. Solution for Java 8 date/time type java.time.LocalDateTime not supported by default

Actually, the exception gives us information about how to fix that problem. We need to Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling Java 8 date/time types.

  • First add Jackson-Datatype-JSR310 dependency in your pom.xml (you can find the current version in Maven Repository):

    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jsr310</artifactId>
      <version>2.6.6</version>
    </dependency>
    
  • Next, we need to register the JavaTimeModule module:

  • Using registerModule method on ObjectMapper:

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    
  • Using findAndRegisterModules method:

    ObjectMapper mapper = new ObjectMapper(); 
    mapper.findAndRegisterModules();
    
  • Using builder() - this is possible since version 2.10:

    ObjectMapper mapper = JsonMapper.builder()
         .findAndAddModules()
         .build();
    

4. Conclusion

In this article we presented how to fix java.lang.IllegalArgumentException: Java 8 date/time type java.time.LocalDateTime not supported by default.

{{ message }}

{{ 'Comments are closed.' | trans }}