Jackson - define empty fields without using JsonSerializer & BeanSerializerModifier Jackson - define empty fields without using JsonSerializer & BeanSerializerModifier json json

Jackson - define empty fields without using JsonSerializer & BeanSerializerModifier


This is easy to do with logic in the getter method:

@JsonInclude(JsonInclude.Include.NON_EMPTY)public class FOO {    private BOO boo = new BOO();    private GOO goo = new GOO();    public BOO getBoo() {        //replace if block with "empty" check logic        if(this.boo.getAaa() == null || this.boo.getBbb() == null) {            return this.boo;        }        return null;    }}

Combined with the @JsonInclude(JsonInclude.Include.NON_EMPTY) instruction, the field will not be included when null.

Of course, as you mentioned, you can add isEmpty() to BOO and call it from the getter method.


You could get the trick overriding the serialization of boo property with a @JsonGetter annotation. I simplified the models just for the sake of the example.

The simplified FOO class:

@JsonInclude(JsonInclude.Include.NON_EMPTY)public class FOO {    private BOO boo = new BOO();        @JsonGetter("boo")    private BOO serializeEmptyBOO() {        if (this.boo.isEmpty()) {            return this.boo;        }        return null;    }    // Getters & setters}

The simplified BOO class:

@JsonInclude(JsonInclude.Include.NON_EMPTY)public class BOO {        @JsonIgnore    public boolean isEmpty() {        // Your isEmpty implementation    }}