Using Jackson ObjectMapper with Java 8 Optional values

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

    Define new getter which will return String instead of Optional.

    public class Test {
        Optional field = Optional.of("hello, world!");
    
        @JsonIgnore
        public Optional getField() {
            return field;
        }
    
        @JsonProperty("field")
        public String getFieldName() {
            return field.orElse(null);
        }
    
    }
    

提交回复
热议问题