Setting default values to null fields when mapping with Jackson
There is no annotation to set default value.
You can set default value only on java class level:
public class JavaObject
{
public String notNullMember;
public String optionalMember = "Value";
}
Use the JsonSetter
annotation with the value Nulls.SKIP
If you want to assign a default value to any param which is not set in json request then you can simply assign that in the POJO itself.
If you don't use @JsonSetter(nulls = Nulls.SKIP)
then the default value will be initialised only if there is no value coming in JSON, but if someone explicitly put a null then it can lead to a problem. Using @JsonSetter(nulls = Nulls.SKIP)
will tell the Json de-searilizer to avoid null
initialisation.
Value that indicates that an input null value should be skipped and the default assignment is to be made; this usually means that the property will have its default value.
as follow:
public class User {
@JsonSetter(nulls = Nulls.SKIP)
private Integer Score = 1000;
...
}
Only one proposed solution keeps the default-value
when some-value:null
was set explicitly (POJO readability is lost there and it's clumsy)
Here's how one can keep the default-value
and never set it to null
@JsonProperty("some-value")
public String someValue = "default-value";
@JsonSetter("some-value")
public void setSomeValue(String s) {
if (s != null) {
someValue = s;
}
}
You can create your own JsonDeserializer and annotate that property with @JsonDeserialize(as = DefaultZero.class)
For example: To configure BigDecimal to default to ZERO:
public static class DefaultZero extends JsonDeserializer<BigDecimal> {
private final JsonDeserializer<BigDecimal> delegate;
public DefaultZero(JsonDeserializer<BigDecimal> delegate) {
this.delegate = delegate;
}
@Override
public BigDecimal deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
return jsonParser.getDecimalValue();
}
@Override
public BigDecimal getNullValue(DeserializationContext ctxt) throws JsonMappingException {
return BigDecimal.ZERO;
}
}
And usage:
class Sth {
@JsonDeserialize(as = DefaultZero.class)
BigDecimal property;
}