Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not instantiate value of type [simple type, class java.time.LocalDate] from String value

Tags:

java

spring

I have a class like this:

@Data
@NoArgsConstructor(force = true)
@AllArgsConstructor(staticName = "of")
public class BusinessPeriodDTO {
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    LocalDate startDate;
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    LocalDate endDate;
}

And I used this class inside another class, let's call it PurchaseOrder

@Entity
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED, force = true)
public class PurchaseOrder {
    @EmbeddedId
    PurchaseOrderID id;

    @Embedded
    BusinessPeriod rentalPeriod;

    public static PurchaseOrder of(PurchaseOrderID id, BusinessPeriod period) {
        PurchaseOrder po = new PurchaseOrder();
        po.id = id;

        po.rentalPeriod = period;

        return po;
    }

And I'm trying to populate a purchaseOrder record using jakson and this JSON:

 {
     "_class": "com.rentit.sales.domain.model.PurchaseOrder",
     "id": 1,
     "rentalPeriod": {
         "startDate": "2016-10-10",
         "endDate": "2016-12-12"
     }
 }

But I have faced with an error:

java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class java.time.LocalDate] from String value ('2016-10-10');

I am sure jakson and popularization works correctly.

like image 522
Jeff Avatar asked Feb 08 '23 03:02

Jeff


1 Answers

Include in your pom.xml:

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

Then in your BusinessPeriodDTO.java import LocalDateDeserializer as follows:

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;

And finally, always in your BusinessPeriodDTO.java file, annotate the interested dates like this:

@JsonDeserialize(using = LocalDateDeserializer.class)
LocalDate startDate;
@JsonDeserialize(using = LocalDateDeserializer.class)
LocalDate endDate;
like image 159
Luca Tampellini Avatar answered Feb 16 '23 04:02

Luca Tampellini