12

I have added the JS310 dependency to Maven and refreshed the dependencies:

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

In the domain:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
LocalDate start;

However, I am receiving this error:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type java.time.LocalDate not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling

DwB
  • 37,124
  • 11
  • 56
  • 82
noumenal
  • 1,077
  • 2
  • 16
  • 36

1 Answers1

28

The error is indicative and explains you haven't registered the JavaTimeModule module like documented at datetime : to register it you can for example do in this way (or other equivalent way explained in the link I added previously, dependly from the jackson library version you are using) :

ObjectMapper mapper = JsonMapper.builder()
    .addModule(new JavaTimeModule())
    .build();
dariosicily
  • 4,239
  • 2
  • 11
  • 17
  • 3
    @noumenal If you are using a version 2.x before 2.9 the code is `ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule());`, both methods with equivalent alternatives are present in the link. I'm seeing you are using 2.13 module, checks if this is the version you are currently using, because these are the methods from official documentation. – dariosicily Nov 02 '21 at 15:16
  • Wow. Learned something new. Thanks. – djangofan Apr 29 '22 at 20:42
  • @djangofan Glad to have helped. – dariosicily Apr 29 '22 at 21:09
  • @dariosicily should this work with spring boot 2.7.x I've tried this while trying to serialize an object from elasticseaech with a Instant field and I'm getting the same error – MetaCoder Dec 07 '22 at 10:42
  • 3
    @MetaCoder For spring boot there is a specific [`spring-boot-starter-json`](https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-json) json starter that includes the `jackson-datatype-jsr310`. – dariosicily Dec 07 '22 at 11:53
  • Thanks for that. Strangely enough even without adding the dependancy if I just remove any and all object mapper configs and when creating the elasticsearch client just do this ```ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper(objectMapper));``` it works...where as ```ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());``` causes it to fail – MetaCoder Dec 07 '22 at 12:10
  • 1
    @MetaCoder Glad to have helped, without exploring the source code a possible way to explain about the success or fail is that when with the import of the `ObjectMapper` it automatically imports all modules including the datetime module. – dariosicily Dec 07 '22 at 16:10