How do I use Jackson JSON mapper with Java 8 LocalDateTime?
org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class java.time.LocalDateTime] from JSON String; no single-String constructor/factory method (through reference chain: MyDTO["field1"]->SubDTO["date"])
If you are using ObjectMapper class of fasterxml, by default ObjectMapper do not understand the LocalDateTime class, so, you need to add another dependency in your gradle/maven :
Now you need to register the datatype support offered by this library into you objectmapper object, this can be done by following :
Now, in your jsonString, you can easily put your java.LocalDateTime field as follows :
By doing all this, your Json file to Java object conversion will work fine, you can read the file by following :
If you are using Jersey then you need to add the Maven dependency (jackson-datatype-jsr310) as the others suggested and register your object mapper instance like so:
When registering Jackson in your resources, you need to add this mapper like so:
There's no need to use custom serializers/deserializers here. Use jackson-modules-java8's datetime module:
This module adds support for quite a few classes:
I had a similar problem while using Spring boot. With Spring boot 1.5.1.RELEASE all I had to do is to add dependency:
If you can't use
jackson-modules-java8
for whatever reasons you can (de-)serialize the instant field as long using@JsonIgnore
and@JsonGetter
&@JsonSetter
:Example:
yields
Update: Leaving this answer for historical reasons, but I don't recommend it. Please see the accepted answer above.
Tell Jackson to map using your custom [de]serialization classes:
provide custom classes:
random fact: if i nest above classes and don't make them static, the error message is weird:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported