杰克逊将缺少的属性反序列化为空可选

杰克逊将缺少的属性反序列化为空可选

问题描述:

假设我有一个这样的课程:

Let's say I have a class like this:

public static class Test {

        private Optional<String> something;

        public Optional<String> getSomething() {
            return something;
        }

        public void setSomething(Optional<String> something) {
            this.something = something;
        }

    }

如果我反序列化此JSON,则会得到一个空的Optional:

If I deserialize this JSON, I get an empty Optional:

{"something":null}

但是如果缺少属性(在本例中为空JSON),则会得到null而不是Optional.我当然可以自己初始化字段,但是我认为最好有一种机制来处理null和缺少的属性.那么有没有办法使杰克逊将缺少的属性反序列化为空的Optional?

But if property is missing(in this case just empty JSON), I get null instead of Optional. I could initialize fields by myself of course, but I think it would be better to have one mechanism for null and missing properties. So is there a way to make jackson deserialize missing properties as empty Optional?

可选实际上并不是要用作字段,而应更多地用作返回值.为什么没有:

Optional is not really meant to be used as a field but more as a return value. Why not have:

public static class Test {
  private String something;
  public Optional<String> getSomething() {
    return Optional.ofNullable(something);
  }
  public void setSomething(String something) {
    this.something = something;
  }
}