Specify a default value for the attribute if null in json by jackson

Suppose I have an ie class

private class Student { private Integer x = 1000; public Integer getX() { return x; } public void setX(Integer x) { this.x = x; } } 

Now suppose json is "{x:12}" and is deserializing, then x will be 12 . But if json is "{}" , then the value is x = 1000 (get from the default value of the attribute declared in the class).

Now, if json is "{x:null}" , then the x value becomes null , but here even in this case I want the x value to be 1000 . How to do it through jackson . Thanks in advance.

I will deserialize the method below if that helps anyway: objectMapper.readValue(<json string goes here>, Student.class);

+7
java json jackson
source share
4 answers
 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()); } 

exit:

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

exit:

1000

0
source share

You can override the setter. Add the @JsonProperty(value="x") annotations to the recipient and customizer to tell Jackson that they can 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; } } 
+3
source share

Consider the JsonDeserializer extension

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 he uses:

 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); 
+1
source share

From json to the object, you can fix this in the customizer and tell Jackson not to use field access, but to use the installer for unmarshalling.

0
source share

All Articles