Java 8 and LocalDate serialization issues with Jackson mapper

Say you have a LocalDate attribute in one of your models in your Spring based RESTful Web Service and you need your clients to send and receive the LocalDate in some form of yyyyMMdd
LocalDate myDate;

Simply add the following dependency to your classpath (pom.xml)

   com.fasterxml.jackson.datatype
   jackson-datatype-jsr310
   2.8.6

And annotate your LocalDate attributes as

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd")
LocalDate myDate;

But what if your project also uses older Date Api? (Say you are using both the original Date and new LocalDate)

Then you might have something like this to set the date format universally across the project to convert all Date instances

@Bean
 public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
     MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
     ObjectMapper objectMapper = new ObjectMapper();
     DateFormat df = new SimpleDateFormat("yyyyMMdd");
     df.setTimeZone(TimeZone.getTimeZone("EST"));
     objectMapper.setDateFormat(df);
     jsonConverter.setObjectMapper(objectMapper);
     return jsonConverter;
 }

Jackson is still on JDK 6. So they have begun a modular plugin approach to support Java 8 features such as the new Date API (LocalDate) etc. To make Jackson play nice with both the old and the new APIs, simply update the above to

@Bean
 public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
     MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
     ObjectMapper objectMapper = new ObjectMapper()
           .registerModule(new ParameterNamesModule())
           .registerModule(new Jdk8Module())
           .registerModule(new JavaTimeModule());
     DateFormat df = new SimpleDateFormat("yyyyMMdd");
     df.setTimeZone(TimeZone.getTimeZone("EST"));
     objectMapper.setDateFormat(df);
     jsonConverter.setObjectMapper(objectMapper);
     return jsonConverter;
 }

Make sure that you also update your pom.xml with the necessary dependencies

   com.fasterxml.jackson.module
   jackson-module-parameter-names


   com.fasterxml.jackson.datatype
   jackson-datatype-jdk8


   com.fasterxml.jackson.datatype
   jackson-datatype-jsr310
   2.8.6

The first dependency in the list adds support for JDK8 datatypes before core Jackson can support them.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.