0

I don't want to include nested objects values in json which are null, but I obtain different result. I have class:

@Data
public class HoldsType {

    @JsonInclude(JsonInclude.Include.NON_NULL)
    protected HoldTypeIndicatorType holdTypeIndicator;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    protected HoldReasonsType holdReasons;
}

And it contains nested HoldTypeIndicatorType class:

@Data
public class HoldTypeIndicatorType {

    @JsonInclude(JsonInclude.Include.NON_NULL)
    protected Boolean dealerAssignment;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    protected Boolean someSpecification;
}

I added there @JsonInclude(JsonInclude.Include.NON_NULL) annotations to exclude those fields from results json, but I receive:

{
 "holdTypeIndicator": {}
}

I tried also adding

  • NON_DEFAULT property, or
  • NON_ABSETNT property, but it's the same.

The problem is here I have tons of fields type: Boolean. What should be the simplest way to add this behavior to ObjectMapper to not include this holdTypeIndicator object, when all Boolean nested values are null, in json? Writing custom Serializable will require adding annotation to all of those fields. Is there any way I can override ObjectMapper default serializer for this?

  • If my understanding is correct and you do not want to include holdTypeIndicator at all, if any of its subfields are null, then perhaps you need to write a custom Deserializer. See https://stackoverflow.com/questions/19158345/custom-json-deserialization-with-jackson – JCompetence Sep 09 '21 at 11:58
  • @SusanMustafa I know I can, but may be there is also another way to override ObjectMapper default serializer? – Janusz Januszewski Sep 09 '21 at 12:31
  • You can add `@JsonInclude(JsonInclude.Include.NON_NULL)` at the class level instead of the field level. You don't have to add it to each individual field. – Christopher Schneider Sep 09 '21 at 12:53

0 Answers0