杰克逊反序列化任意反应器NPE

时间:2018-09-05 20:04:03

标签: jackson

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern UIntPtr CreateService(UIntPtr SC_HANDLE, string lpSvcName, string lpDisplayName,
        uint dwDesiredAccess, uint dwServiceType, uint dwStartType, uint dwErrorControl, string lpPathName,
        string lpLoadOrderGroup, string lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);

当我将@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); } } 与以下json字符串一起使用时:

objectmepper.readValue(json_string, Payer.class)

我得到了NPE。由于我有{ "name": "fakeName", "state": "verifird" } ,因此应该将@JsonAnySetter字符串放入state中,我想知道为什么我在这里得到NPE?

1 个答案:

答案 0 :(得分:0)

name类中包含Payer的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}