简体   繁体   中英

How to tell Jackson to ignore a Object with EMPTY or NULL fields during serialization?

I know about these annotations @JsonInclude(JsonInclude.Include.NON_NULL) and @JsonInclude(JsonInclude.Include.EMPTY) but in my case it's doesn't work.

My case is:

I have some class (entity (SomeClass)) with some other entity inside (SomeObject)

    @Data
    public class SomeClass {
        private String fieldOne;
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private String fieldTwo;
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private SomeObject someObject;
    }

Entity - SomeObject

@Data
public class SomeObject {
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String name;
}

Main class

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        SomeClass someClass = new SomeClass();
        someClass.setFieldOne("some data");

        SomeObject someObject = new SomeObject();
        someObject.setName(null);
        someClass.setSomeObject(someObject);

        ObjectMapper objectMapper = new ObjectMapper();
        String someClassDeserialized = objectMapper.writeValueAsString(someClass);
        System.out.println(someClassDeserialized);
    }
}

Output

{"fieldOne":"some data","someObject":{}}

The final output should be, without object (SomeObject) with null or empty fields:

{"fieldOne":"some data"}

I think only custom logic can be applied here. You need to use @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = YourFilter.class) and create custom YourFilter class. You can create base interface with boolean method, and override it in all classes which needs to be filtered out based on nullability of all/desired fields in the class. Or you can parse @JsonInclude(JsonInclude.Include.NON_NULL) annotations in this method, to get all fields, which nullability you need to check.

https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM