Reputation: 273
Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling
I have been getting this error in my spring boot project that uses Gradle. I added the below given Gradle dependency for jsr310 as well, still it didn't work.
implementation group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.13.3'
How can I fix this error? My project uses Java 17 and Spring 2.6.7.
Upvotes: 17
Views: 37675
Reputation: 104
new ObjectMapper().registerModule(new JavaTimeModule());
Hope, this helps you.
Upvotes: 9
Reputation: 5165
JavaTimeModule
should be registered explicitly:
@Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
return mapper;
}
}
UPDATE:
The first solution should be used with jackson-datatype-jsr310
versions 2.x
before 2.9
. Since you added version 2.13.3
, the module should be registered as shown below, according to the answer.
@Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
return JsonMapper.builder()
.addModule(new JavaTimeModule())
.build();
}
}
UPDATE 2:
Starting with Jackson 2.2, Modules can be automatically discovered using the Service Provider Interface (SPI) feature. You can activate this by instructing an ObjectMapper to find and register all Modules:
// Jackson 2.10 and later
ObjectMapper mapper = JsonMapper.builder()
.findAndAddModules()
.build();
// or, 2.x before 2.9
ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();
For reference: jackson-modules-java8 - Registering modules
Upvotes: 18