@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?
在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中排除字段来解决问题。