When deserializing a variety of JSON messages, I want to provide a default value for attributes of a certain type. It is generally suggested to simply specify the value in the Class, but this is error-prone if you have to do this across many Classes. You might forget one and end up with null
instead of a default value. My intention is to set every property that is an Optional<T>
to Optional.absent
. Since null
is exactly what Optional
is trying to eliminate, using them with Jackson has proven to be frustrating.
Most features of Jackson that allow you to customize the deserialization process focus on the JSON that is the input, not around the process of instantiating the Object that you are deserializing into. The closest I seem to be getting to a general solution is by building my own ValueInstantiator
, but there are two remaining issues I have:
- how do I make it only instantiate
Optional
asabsent
but not interfere with the rest of the instantiation process? - how do I wire the end result into my
ObjectMapper
?
UPDATE: I want to clarify that I am looking for a solution that does not involve modifying each Class that contains Optional
's. I'm opposed to violating the DRY principle. Me or my colleagues should not have to think about having to do something extra every time we add Optional
's to a new or existing Class. I want to be able to say, "make every Optional field in every Class I deserialize into, pre-filled with Absent
", only once, and be done with it.
That means the following are out:
- abstract parent class (need to declare)
- custom Builder/Creator/JsonDeserializer (needs annotation on each applicable class)
- MixIn's? I tried this, combined with reflection, but I don't know how to access the Class I'm being mixed into...