Skip to content
Advertisement

Java 8 LocalDate Jackson format

For java.util.Date when I do

JavaScript

then in JSON request when I send

JavaScript

it works.

How should I do this for Java 8’s LocalDate field??

I tried having

JavaScript

It didn’t work.

Can someone please let me know what’s the right way to do this..

Below are dependencies

JavaScript

Advertisement

Answer

I was never able to get this to work simple using annotations. To get it to work, I created a ContextResolver for ObjectMapper, then I added the JSR310Module (update: now it is JavaTimeModule instead), along with one more caveat, which was the need to set write-date-as-timestamp to false. See more at the documentation for the JSR310 module. Here’s an example of what I used.

Dependency

JavaScript

Note: One problem I faced with this is that the jackson-annotation version pulled in by another dependency, used version 2.3.2, which cancelled out the 2.4 required by the jsr310. What happened was I got a NoClassDefFound for ObjectIdResolver, which is a 2.4 class. So I just needed to line up the included dependency versions

ContextResolver

JavaScript

Resource class

JavaScript

Test

curl -v http://localhost:8080/api/person
Result: {"birthDate":"2015-03-01"}

curl -v -POST -H "Content-Type:application/json" -d "{"birthDate":"2015-03-01"}" http://localhost:8080/api/person
Result: 2015-03-01


See also here for JAXB solution.

UPDATE

The JSR310Module is deprecated as of version 2.7 of Jackson. Instead, you should register the module JavaTimeModule. It is still the same dependency.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement