FasterXML / jackson-modules-java8

Set of support modules for Java 8 datatypes (Optionals, date/time) and features (parameter names)
Apache License 2.0
399 stars 116 forks source link

Allow `Optional` deserialization for "absent" value as Java `null` (like other Reference types), not "empty" #251

Closed cowtowncoder closed 1 year ago

cowtowncoder commented 1 year ago

So, for case like:

public class OptionalnBean {
   Optional<String> value;

   @JsonCreator
   public OptionalnBean(@JsonProperty("value") Optional<String> value) {
     this.value = value;
   }
}

with JSON like

{ }

current handling would assign Optional.empty() to value. But other reference types, like AtomicReference will instead assign null. This is to differentiate case of reading JSON like:

{ "value" : null }

in which value for all reference types becomes "empty" value (new AtomicReference<>, Optional.empty()).

This should be fixed for 2.14. But since this is a behavioral change it is also necessary to add configurability to allow old behavior, at least for 2.x. And to maximize backwards compatibility we probably have to default to old and (IMO) sub-optimal handling.

cowtowncoder commented 1 year ago

Ok, to configure new behavior -- absent (missing) Optionals becoming Java nulls you need to configure module, register it. So:

        Jdk8Module module = new Jdk8Module()
                .configureReadAbsentAsNull(true);
        final ObjectMapper mapper = JsonMapper.builder()
                .addModule(module)
                .build();

This will be in 2.14.0 release.