jackson-databind icon indicating copy to clipboard operation
jackson-databind copied to clipboard

Allow JsonDeserializer to provide default value for "missing" properties

Open stevenschlansker opened this issue 11 years ago • 3 comments

This came up in https://github.com/FasterXML/jackson-datatype-jdk8/issues/2 When deserializing a bean containing Optional<T> fields, the value Optional.empty() makes more sense than filling in null for properties that are entirely missing from the JSON.

stevenschlansker avatar Nov 18 '14 17:11 stevenschlansker

(Once this issue is closed, it may make sense to re-open the above issue)

stevenschlansker avatar Nov 18 '14 17:11 stevenschlansker

I tried really hard to support this using existing features like injectables, default "null" values, and so on, but they have pretty inconsistent behavior under common cases like creator vs field properties. Even addressing those still leaves a couple ambiguous cases though. I ended up side-stepping them and just using some fairly invasive wrapping/delegating deserializers and doing full TreeNode parsing. It is more expensive but those use cases did not involve frequent object ser/deser -- mostly configuration type stuff.

The best I could come up with for maintaining streaming (no full TreeNode parsing) with reasonable performance was passing around a bit field indexed by property id that is toggled whenever a property is found and deserialized. A single primitive long, for instance, could track up to 64 fields that are either required or have special defaults, and would certainly have negligible overhead... but then you have an awkward, hard coded limit so might be worth abstracting anyway.

It wasn't really possible to do that from the APIs made available for customization though. Or at least not without being even more incompatible with other components.

tea-dragon avatar Nov 19 '14 22:11 tea-dragon

FWTW, Jackson 2.6 actually does support injection of default values for Creator properties. Default value is defined as value that matching JsonDeserializer method getNullValue(DeserializationContext ctxt) returns. I have also ensured that all "Optional" type serializers will return suitable "absent" instance for these cases.

cowtowncoder avatar May 30 '15 00:05 cowtowncoder