假设我上课
private class Student {
private Integer x = 1000;
public Integer getX() {
return x;
}
public void setX(Integer x) {
this.x = x;
}
}
现在假设json是
"{x:12}"
并进行反序列化,则x
的值为12
。但是,如果json是"{}"
,则x = 1000
的值(get来自于在类中声明的属性的默认值)。现在,如果json是
"{x:null}"
,则x的值变为null
,但是即使在这种情况下,我也希望x
的值是1000
。 如何通过jackson 进行操作。提前致谢。我通过以下方法反序列化,如果仍然有帮助的话:
objectMapper.readValue(<json string goes here>, Student.class);
最佳答案
您应该能够覆盖 setter 。将@JsonProperty(value="x")
批注添加到getter和setter中,以让Jackson知道使用它们:
private class Student {
private static final Integer DEFAULT_X = 1000;
private Integer x = DEFAULT_X;
@JsonProperty(value="x")
public Integer getX() {
return x;
}
@JsonProperty(value="x")
public void setX(Integer x) {
this.x = x == null ? DEFAULT_X : x;
}
}