5

I am getting this error (note that we are talking about LocalDate, not LocalDateTime) :

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDate (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2012-03-12')

I have been searching for this problem, and tried the "tricks" that are mentioned frequently in other answers, such as (I have been trying one by one of these tricks, plus I have been combining them in different ways) :

  1. Include com.fasterxml.jackson.datatype:jackson-datatype-jsr310
  2. Tell Jackson ObjectMapper to use JavaTimeModule by registering the module through a bean
  3. Try using jackson-module-kotlin
  4. Try more dependencies from Jackson (different combinations)
  5. Set write-dates-as-timestamps in the spring config to false
  6. Add @JsonCreator constructor to the data class

My dto data class looks like this :

 data class DateDto (
    @JsonProperty("date")
    @JsonDeserialize(using = LocalDateDeserializer::class)
    @JsonSerialize(using = LocalDateSerializer::class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    val date : LocalDate
 );

However, I have no luck with these tricks, and I don't understand what I am doing wrong.

Why is this so difficult ? Am I missing something very obvious ? I am using Spring Boot 2.2.7, Kotlin 1.3.70, jackson-datatype-jsr310 2.11.1.

user1511956
  • 784
  • 3
  • 9
  • 22

1 Answers1

16

It turns out that step number 2) actually solves my problem here. I need to register a JavaTime module for the ObjectMapper. I must have done something wrong to not make this work earlier.

For example :

 var mapper = ObjectMapper() 
 .registerModule(KotlinModule())
 .registerModule(JavaTimeModule())

 mapper.readValue<DateDto>(message)

Also, there is no need to include com.fasterxml.jackson.datatype:jackson-datatype-jsr310 for example. You just include jackson-module-kotlin like so :

    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-kotlin</artifactId>
    </dependency>

To use the ObjectMapper and the jackson-module-kotlin seems to be sufficient! However, I would love some good resources / books about serialization and Jackson. How it works under the hood, and how to relate to it in practice. It is a lot of fragmented information about it. I will edit this answer if I find something.

user1511956
  • 784
  • 3
  • 9
  • 22