Using Jackson ObjectMapper with Java 8 Optional values

前端 未结 7 1878
长发绾君心
长发绾君心 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:46

    Similar to @Manikandan's answer but add @JsonProperty to the private field instead of a getter so you don't expose your work around on the public api.

    public class Test {
    
        @JsonProperty("field")
        private String field;
    
        @JsonIgnore
        public Optional<String> getField() {
            return Optional.of(field); // or Optional.ofNullable(field);
        }
    }
    
    0 讨论(0)
提交回复
热议问题