serialize/deserialize java 8 java.time with Jackson JSON mapper
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 :
compile 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.7.3'
Now you need to register the datatype support offered by this library into you objectmapper object, this can be done by following :
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
Now, in your jsonString, you can easily put your java.LocalDateTime field as follows :
{
"user_id": 1,
"score": 9,
"date_time": "2016-05-28T17:39:44.937"
}
By doing all this, your Json file to Java object conversion will work fine, you can read the file by following :
objectMapper.readValue(jsonString, new TypeReference<List<User>>() {
});
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:
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime ignoreUntil;
provide custom classes:
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException {
arg1.writeString(arg0.toString());
}
}
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser arg0, DeserializationContext arg1) throws IOException {
return LocalDateTime.parse(arg0.getText());
}
}
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
There's no need to use custom serializers/deserializers here. Use jackson-modules-java8's datetime module:
Datatype module to make Jackson recognize Java 8 Date & Time API data types (JSR-310).
This module adds support for quite a few classes:
- Duration
- Instant
- LocalDateTime
- LocalDate
- LocalTime
- MonthDay
- OffsetDateTime
- OffsetTime
- Period
- Year
- YearMonth
- ZonedDateTime
- ZoneId
- ZoneOffset