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

When I use objectmepper.readValue(json_string, Payer.class) with following json string:

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

I get NPE. Since I have @JsonAnySetter, the state string should be put into additionalProperties, I'd like to know why do I get NPE here?

Cosaic
  • 497
  • 2
  • 9
  • 15

2 Answers2

0

Include getter and setter for name in Payer class:

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

}

Parse the 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());
  }

Output:

fakeName
{state=verifird}
S.K.
  • 3,597
  • 2
  • 16
  • 31
  • I forgot to mention that I have already `@Data` annotation of lombok, it has getter and setter. – Cosaic Sep 06 '18 at 13:08
0

It is probably too late but I have a similar issue and discovered the problem was in the Lombok builder. I believe the same might be issued by the constructor with additionalProperties parameter without @JsonIgnore, so you should check if this annotation is added to the generated constructor parameter. (it could be added using lombok.config)

I solve the problem by excluding the field from the builder according to How to exclude property from Lombok builder?.