Java8 LocalDateTime to Joda LocalDateTime with jackson

Yesterday I fought a problem that didn’t seem to take as much time as it actually did, so I decided to write a few lines to share the learned lesson. I had the following case: a spring boot rest service, that returns a JSON object, and a consumer that reads this object using RestTemplate. All was great […]

by Iskren Ivanov

March 10, 2017

2 min read

software - Java8 LocalDateTime to Joda LocalDateTime with jackson

Yesterday I fought a problem that didn’t seem to take as much time as it actually did, so I decided to write a few lines to share the learned lesson.

I had the following case: a spring boot rest service, that returns a JSON object, and a consumer that reads this object using RestTemplate. All was great but the fact that this object contains java.time.LocalDateTime in the service that had to be transformed to org.joda.time.LocalDateTime in the consumer. I decided not to implement custom deserializer and here is the other way I managed to make it work solving lots of org.springframework.http.converter.HttpMessageNotReadableException

The service

The problem in the service was that the date in the result looked like

"departureTimeUTC": {
    "month": "MARCH",
    "year": 2017,
    "dayOfMonth": 8,
    "dayOfWeek": "WEDNESDAY",
    "dayOfYear": 67,
    "hour": 2,
    "minute": 40,
    "nano": 0,
    "second": 0,
    "monthValue": 3,
    "chronology": {
      "id": "ISO",
      "calendarType": "iso8601"
    }
  },

After adding the following maven dependency

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

And updating to false the write-dates-as-timestamps property in application.yml

spring:
  jackson:
    serialization:
      write-dates-as-timestamps: false

Got the nicer result

"departureTimeUTC": "2017-01-05T20:23:00"

The client

In the client the following dependency had to be added

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-joda</artifactId>
</dependency>

And then the RestTemplate had to “learn” about the JodaModule

RestTemplate restTemplate = new RestTemplate();

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());

List<HttpMessageConverter<?>> converters = new ArrayList<>();
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
jsonConverter.setObjectMapper(objectMapper);
converters.add(jsonConverter);
restTemplate.setMessageConverters(converters);



 

Categories

Java Expert at Dreamix