We're migrating from Joda to Java Time. Currently we use DateTime of Joda in our entity. AFAIK DateTime is equivalent to two types in Java: OffsetDateTime and ZonedDateTime. Since we're going to persist them in DB, we're gonna use OffsetDateTime (any comment on this?).
Now the problem is how to configure Jackson's ObjectMapper properly.
All examples I found on the web are about local types for which Jackson's already provided de/serializer implementations (e.g. LocalDateTime, LocalDateTimeSerializer and LocalDateTimeDeserializer).
I finally managed to do something like this:
public class OffsetDateTimeSerializer extends StdSerializer<OffsetDateTime> {
private final DateTimeFormatter formatter; // We need custom format!
public OffsetDateTimeSerializer(DateTimeFormatter formatter) {
super(OffsetDateTime.class);
this.formatter = formatter;
}
@Override
public void serialize(OffsetDateTime value, JsonGenerator generator, SerializerProvider provider) throws IOException {
generator.writeString(value.format(formatter));
}
}
and
public class OffsetDateTimeDeserializer extends StdDeserializer<OffsetDateTime> {
private final DateTimeFormatter formatter; // We need custom format!
public OffsetDateTimeDeserializer(DateTimeFormatter formatter) {
super(OffsetDateTime.class);
this.formatter = formatter;
}
@Override
public OffsetDateTime deserialize(JsonParser parser, DeserializationContext ctx) throws IOException {
return OffsetDateTime.parse(parser.readValueAs(String.class), formatter);
}
}
Now my question is what is the best way to configure Jackson's ObjectMapper to de/serialize Java 8 date-time values?
UPDATE: the accepted answer does not really solve my problem (read the discussion in comments). I ended up with a little simpler code than what I proposed in the above. See my own answer as well.