提问者:小点点

Jackson反序列化anysetterNPE


@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);
    }
}

当我使用object tmeper. readValue(json_string,Payer.class)与以下json字符串:

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

我NPE。因为我有@JsonAnySetter状态字符串应该放入addtionalProperties,我想知道为什么我在这里NPE?


共2个答案

匿名用户

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}

匿名用户

可能太晚了,但我也遇到了类似的问题,发现问题出在Lombok构建器中。我相信同样的问题可能是由带有addtionalProperties参数的构造函数发出的,而没有@JsonIgnore,所以你应该检查这个注释是否被添加到生成的构造函数参数中。(可以使用lombok. config添加)

我根据如何从Lombok builder中排除属性?通过从builder中排除字段来解决问题。