-1

I need to consume a Rest API using Java/Spring (RestTemplate). After doing some smoke test with Postman I see the dates fields have this structure

"clipStartDate": {
  "__type": "Date",
  "iso": "2010-09-14T00:00:00.000Z"
}

I tried to map this fields in my DTO using java.time.LocalDateTime. But I'm getting a serialization exception. (org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of java.time.LocalDateTime)

What is the best practice in this case?

2 Answers2

1

This error you're seeing means that your ObjectMapper is not configured properly. In Spring Boot this comes autoconfigured out of the box, so if you use e.g Spring Boot 2.2 this error will disappear.

However if for some reason you don't have this possibility, then you need to configure an ObjectMapper with an additional module called JavaTimeModule.

  @Bean
  public ObjectMapper objectMapper(){
    return new ObjectMapper()
        .registerModule(new JavaTimeModule());
  }

Here's a suplementary article describing how to further customize ObjectMapper

Yayotrón
  • 1,759
  • 16
  • 27
0

You should use java.time.Instant and it will map properly. The format in your question is of java.time.Instant, So define the field as Instant and it should work.

Add @JsonDeserialize(using=InstantDeserializer.class) on top of property like following:

@JsonDeserialize(using=InstantDeserializer.class)
private final Instant instant;
  • Hi. I'm getting the same exception org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `java.time.Instant` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.Instant` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator) – fredyjimenezrendon May 19 '21 at 02:31
  • Add `@JsonDeserialize(using=InstantDeserializer.class)` on top of the property declaration. – Vipulkumar Gorasiya May 19 '21 at 04:44
  • Can you please share the code of pom.xml and any configuration done around `ObjectMapper`? That will help better understand the situation in your case. – Vipulkumar Gorasiya May 19 '21 at 05:19
  • Hi. I'm not using Maven. This project is using ant – fredyjimenezrendon May 19 '21 at 14:01
  • Can you please share versions of frameworks like Spring, Jackson and Sample/glimpse of code, if it is not still not solved? – Vipulkumar Gorasiya May 21 '21 at 04:20