Jackson反序列化Anysetter

zy1mlcev  于 2023-05-29  发布在  其他
关注(0)|答案(2)|浏览(140)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Payer{
    private String name;

    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
}

当我使用objectmepper.readValue(json_string, Payer.class)和以下json字符串时:

{
   "name": "fakeName",
   "state": "verifird"
}

我得到了NPE。因为我有@JsonAnySetter,所以state字符串应该放入additionalProperties中,我想知道为什么我在这里得到了NPE?

waxmsbnn

waxmsbnn1#

Payer类中包含name的getter和setter:

@JsonInclude(JsonInclude.Include.NON_NULL)
class Payer{
    private String name;

    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

}

解析Json:

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    String json_string = "{\n" +
        "   \"name\": \"fakeName\",\n" +
        "   \"state\": \"verifird\"\n" +
        "}";
    Payer readValue = mapper.readValue(json_string , Payer.class);
    System.out.println(readValue.getName());
    System.out.println(readValue.getAdditionalProperties());
  }

输出:

fakeName
{state=verifird}
n3ipq98p

n3ipq98p2#

这可能是太晚了,但我有一个类似的问题,并发现问题是在Lombok岛建设者。我相信同样的情况也会发生在带有additionalProperties参数而没有@JsonIgnore的构造函数上,所以你应该检查一下这个注解是否被添加到了生成的构造函数参数中。(可以使用lombok.config添加)
我通过根据How to exclude property from Lombok builder?从构建器中排除字段来解决这个问题。

相关问题