You can write your own deserializer to handle the default value. Effectively, you extend the appropriate deserializer for the type of object to be deserialized, get a deserialized value, and if it is null just returns the corresponding default value.
Here is a quick way to do this with strings:
public class DefaultStringModule extends SimpleModule { private static final String NAME = "DefaultStringModule"; private static final String DEFAULT_VALUE = "[DEFAULT]"; public DefaultStringModule() { super(NAME, ModuleVersion.instance.version()); addDeserializer(String.class, new DefaultStringDeserializer()); } private static class DefaultStringDeserializer extends StdScalarDeserializer<String> { public DefaultStringDeserializer() { super(String.class); } public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException { String deserialized = jsonParser.getValueAsString();
To use this with ObjectMapper , you can register the module in an instance:
ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new DefaultStringModule());
To handle the default values for fields not present in JSON, I usually saw this using the builder class, which will build the class using the provided values, and add the default values for the missing fields. Then, in a deserialized class (e.g. MyClass ) add the @JsonDeserialize(builder = MyClass.Builder.class) annotation @JsonDeserialize(builder = MyClass.Builder.class) to tell Jackson to deserialize MyClass using the builder class.
source share