Skip to content
Advertisement

How do you specify default values for Jackson deserialization

JavaScript

Up here is my Controller code.

JavaScript

Up here is my User class code.

JavaScript

When I POST the JSON above, I get the age property to be null.

I want Jackson to deserialize the empty fields ("" or null) in JSON with default values.

Like this:

JavaScript

What should I do?

Advertisement

Answer

You can define a custom getter property where setting your default value in case of null.

JavaScript

Note that you can’t change the setAge method because it is not invoked in this case, infact there is no age field that will inform Jackson to call that method.


An alternative is to use a custom constructor and use the JsonSetter annotation with the value Nulls.SKIP

Value that indicates that an input null value should be skipped and no assignment is to be made; this usually means that the property will have its default value.

as follow:

JavaScript

The @JsonSetter is present in package com.fasterxml.jackson.annotation and can be imported as dependency in maven using

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement