Jackson meets Java 8

This post shows how to use Java 8 features in value objects with FasterXML/jackson .

We’re going to test the serialisation with to Lombok enhanced example classes:

@Value
@AllArgsConstructor
public static class Java8Optional {
    Optional<Boolean> sample;
}

and

@Value
@AllArgsConstructor
public static class Java8DateTime {
    LocalDate localDate;
    LocalDateTime localDateTime;
}

After some time looking at the resources listed below I ended up with the following ObjectMapper configuration:

private ObjectMapper getJdk8ObjectMapper() {
    return new ObjectMapper()
            .registerModule(new JavaTimeModule()
                    .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(ISO_DATE_TIME)))
            .registerModule(new Jdk8Module())
            .configure(WRITE_DATES_AS_TIMESTAMPS, false);
}

This setup can be easily tested with Junit:

In shouldSerializeJava8OptionalIfPresent we check that the Option is serialised correctly if present:

@Test
public void shouldSerializeJava8OptionalIfPresent() throws JsonProcessingException {
    String actual = getJdk8ObjectMapper().writeValueAsString(new Java8Optional(of(true)));

    assertEquals("{\"sample\":true}", actual);
}

Missing optional values should be serialised to null values:

@Test
public void shouldSerializeJava8OptionalAsNullValueIfNotPresent() throws JsonProcessingException {
    String actual = getJdk8ObjectMapper().writeValueAsString(new Java8Optional(empty()));

    assertEquals("{\"sample\":null}", actual);
}

And last but not least the java.time example:

@Test
public void shouldSerializeJava8Instant() throws JsonProcessingException {

    String actual = getJdk8ObjectMapper()
            .writeValueAsString(new Java8DateTime(LocalDate.of(2017, 10, 2),
                    LocalDateTime.of(2017, 10, 2, 11, 33)));

    assertEquals("{\"localDate\":\"2017-10-02\",\"localDateTime\":\"2017-10-02T11:33:00\"}", actual);
}

For more information please check the following short compilation of useful resources I encountered while looking into this topic:

Happy time with Jackson!