Using Jackson ObjectMapper with Java 8 Optional values

前端 未结 7 1879
长发绾君心
长发绾君心 2020-12-01 05:03

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

public class Test {
    Optional field = Optional.of(\"         


        
7条回答
  •  时光取名叫无心
    2020-12-01 05:43

    The Optional class has a value field, but no standard getter/setter for it. By default, Jackson looks for getters/setters to find class properties.

    You can add a custom Mixin to identify the field as a property

    final class OptionalMixin {
        private Mixin(){}
        @JsonProperty
        private Object value;
    }
    

    and register it with your ObjectMapper.

    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixInAnnotations(Optional.class, OptionalMixin.class);
    

    You can now serialize your object.

    System.out.println(mapper.writeValueAsString(new Test()));
    

    will print

    {"field":{"value":"hello, world!","present":true}}
    

    Consider also looking at jackson-datatype-guava. There's a Jackson Module implementation for Guava types including their Optional. It's possibly more complete than what I've shown above.

提交回复
热议问题