I'm using Jackson and I have some JSON schema objects set up something like this:
@JsonInclude(JsonInclude.Include.NON_EMPTY) public class Person { String name; Child child = new Child(); Sibling sibling = new Sibling(); public String getName() { return name; } public void setName(String name) { this.name = name; } public Child getChild() { return child; } public void setChild(Child child) { this.child = child; } public Sibling getSibling() { return sibling; } public void setSibling(Sibling sibling) { this.sibling = sibling; } } @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Child { String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Sibling { String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } I'm attempting to ignore all fields that are null or empty, which works fine. But I also want to ignore objects with fields that are all null or empty. For example:
Person person = new Person(); person.setName("John Doe"); ObjectMapper mapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(person); The resulting JSON string is {"name":"John Doe","child":{},"sibling":{}}, but I want it to be {"name":"John Doe"}. Child and Sibling need to be initialized when Person is created so I don't want to change that. Is there a way to make Jackson treat objects with null fields as null with a custom serializer? I've seen examples of using custom serializers for specific types of objects but I need one that would work for any object.