Using Jackson ObjectMapper with Java 8 Optional values

asieira picture asieira · Sep 5, 2014 · Viewed 50.3k times · Source

I was trying to use Jackson to write a class value to JSON that has Optional as fields:

public class Test {
    Optional<String> field = Optional.of("hello, world!");

    public Optional<String> getField() {
        return field;
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(new Test()));
    }
}

When executed, this class generates the following output:

{"field":{"present":true}}

I understand the present/not present field being included and could work around it when reading the JSON data, however I can't get around the fact that the actual content of the optional is never written to the output. :(

Any workarounds here except not using ObjectMapper at all?

Answer

Jonas picture Jonas · Dec 3, 2014

You could use jackson-datatype-jdk8 which is described as:

Support for new JDK8-specific types, such as Optional

In order to do this:

  • add com.fasterxml.jackson.datatype:jackson-datatype-jdk8 as a dependency
  • register the module with your object mapper: objectMapper.registerModule(new Jdk8Module());