Java – if the value in JSON is null, the default value is provided for the property
•
Java
Suppose I have a class, that is
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 deserialized, then the value of X is 12 However, if JSON is "{}", then x = 1000 (get is the default value from the attribute, which will be announced in class)
Now, if JSON is "{X: null}", the value of X becomes null, but even in this case, I want the value of X to be 1000 How to do this through Jackson Thank you in advance
I deserialize if it still helps: objectmapper Readvalue (< JSON string here >, student. Class);
Solution
You should be able to override the setter Add @ jsonproperty (value = "X") comments to getters and setters to let Jackson know how 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; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码