假设我有班级,即
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
。 如何通过杰克逊来做到这一点。提前谢谢。
我通过以下方法反序列化,如果它仍有帮助:
objectMapper.readValue(<json string goes here>, Student.class);
答案 0 :(得分:3)
您应该可以覆盖设置器。将@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;
}
}
答案 1 :(得分:1)
考虑延长JsonDeserializer
自定义反序列化器:
public class StudentDeserializer extends JsonDeserializer<Student> {
@Override
public Student deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = p.getCodec().readTree(p);
// if JSON is "{}" or "{"x":null}" then create Student with default X
if (node == null || node.get("x").isNull()) {
return new Student();
}
// otherwise create Student with a parsed X value
int x = (Integer) ((IntNode) node.get("x")).numberValue();
Student student = new Student();
student.setX(x);
return student;
}
}
并且它的使用:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Student.class, new StudentDeserializer());
mapper.registerModule(module);
Student readValue = mapper.readValue(<your json string goes here>", Student.class);
答案 2 :(得分:0)
从json到object,你可以在setter中修复它并告诉Jackson不要使用Field访问,而是使用setter进行解组。
答案 3 :(得分:0)
public class Student {
private Integer x = Integer.valueOf(1000);
public Integer getX() {
return x;
}
public void setX(Integer x) {
if(x != null) {
this.x = x;
}
}
}
这对我有用。
测试代码1:
public static void main(String[] args) throws IOException {
String s = "{\"x\":null}";
ObjectMapper mapper = new ObjectMapper();
Student ss = mapper.readValue(s, Student.class);
System.out.println(ss.getX());
}
<强>输出:强>
1000
测试代码2:
public static void main(String[] args) throws IOException {
String s = "{}";
ObjectMapper mapper = new ObjectMapper();
Student ss = mapper.readValue(s, Student.class);
System.out.println(ss.getX());
}
<强>输出:强>
1000