[jackson] Handle LocalDate for json

Post Java 8, LocalDate has become mainstream. Of course, Joda Time, from which LocalDate derives, was quite popular as well. I was trying to convert LocalDate to and from json.

Consider the below simple Person POJO:

 

The below code converts a Person to Json:

The generated json is as below:

Notice that the dateOfBirth field has lots of attributes. The next logical thing to do would be to take this string and try to un-marshall it to Java Object:

However, this results in the below exception:

 

Solution

Its very easy to solve it. We would need to add the LocalDate type module in pom.xml:

To enable it:

Now we can just go our usual way of using the ObectMapper. Note that now the json string now becomes more concise:

Sources

The entire project is here:

https://github.com/paawak/blog/tree/master/code/json-inheritance-demo

The full test case is here:

https://github.com/paawak/blog/blob/master/code/json-inheritance-demo/src/test/java/com/swayam/demo/json/simple/LocalDateJsonTest.java

 

Leave a Reply

Your email address will not be published. Required fields are marked *