give a default value for an attribute if the value is null in json by jackson
You should be able to override the setter. Add the @JsonProperty(value="x")
annotations to the getter and setter to let Jackson know to use them:
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;
}
}
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;
}
}
}
This works for me........
Test code 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());
}
output:
1000
Test code 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());
}
output:
1000
Consider extending JsonDeserializer
custom deserializer:
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;
}
}
and it's use:
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);