java - Implicit default values when deserializing JSON using Jackson -


when deserializing variety of json messages, want provide default value attributes of type. generally suggested specify value in class, error-prone if have across many classes. might forget 1 , end null instead of default value. intention set every property optional<t> optional.absent. since null optional trying eliminate, using them jackson has proven frustrating.

most features of jackson allow customize deserialization process focus on json input, not around process of instantiating object deserializing into. closest seem getting general solution building own valueinstantiator, there 2 remaining issues have:

  • how make instantiate optional absent not interfere rest of instantiation process?
  • how wire end result objectmapper?

update: want clarify looking solution not involve modifying each class contains optional's. i'm opposed violating dry principle. me or colleagues should not have think having every time add optional's new or existing class. want able say, "make every optional field in every class deserialize into, pre-filled absent", once, , done it.

that means following out:

  • abstract parent class (need declare)
  • custom builder/creator/jsondeserializer (needs annotation on each applicable class)
  • mixin's? tried this, combined reflection, don't know how access class i'm being mixed into...

specifically java.lang.optional, there module jackson guys themselves: https://github.com/fasterxml/jackson-datatype-jdk8

guava optional covered https://github.com/fasterxml/jackson-datatype-guava

it create optional.absent null's, not absent json values :-(.

see https://github.com/fasterxml/jackson-databind/issues/618 , https://github.com/fasterxml/jackson-datatype-jdk8/issues/2.

so you're stuck initializing optionals should initialize collections. practice, should able enforce it.

private optional<xxx> xxx = optional.absent(); private list<yyy> yyys = lists.newarraylist(); 

Comments