Jackson serialising Optional with null value for YAML

Viewed 502

Currently I am using the YAMLFactory to configure the ObjectMapper to serialise and deserialise Pojos <=> YAML, however it writes null values in serialisation despite attempting the usual tricks in Jackson.

Annotating with @JsonInclude(JsonInclude.Include.NON_NULL) on the class level or the field level has no affect. I have also tried annotating classes with @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) with no affect either. How do you achieve this when using the YAMLFactory?

I have found a similar question but the use case does not appear to be the same. To be clear I am trying to omit the field altogether.

Edit: Here is an example (I am also using Lombok)

@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class QueueProperties extends Properties {

    @JsonProperty("QueueName")
    private String queueName;

    @JsonProperty("RedrivePolicy")
    private RedrivePolicy redrivePolicy;

    public Optional<RedrivePolicy> getRedrivePolicy() {
        return Optional.ofNullable(redrivePolicy);
    }
}

when serialized:

Properties:
  QueueName: 471416d1-3643-4d5a-a033-65f22757dcaf-chargeback-paypal-ingestion-ingest_dispute
  RedrivePolicy: null

ObjectMapper configuration:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES));                                                          
mapper.registerModule(new Jdk8Module());
1 Answers

getRedrivePolicy getter method always returns not-null object, even so, Optional could reference to null. In this case, you should skip empty objects. Optional with null is considered as empty and we can use JsonInclude.Include.NON_EMPTY for it. You can keep @JsonInclude(JsonInclude.Include.NON_NULL) on class level and add NON_EMPTY only for given getter:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public Optional<Object> getRedrivePolicy() {
    return Optional.ofNullable(redrivePolicy);
}
Related