1

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"}
Alexandr Kovalenko
  • 934
  • 1
  • 12
  • 13
  • Does this answer your question? [How to tell Jackson to ignore a field during serialization if its value is null?](https://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null) – Lemmy Apr 27 '20 at 08:06
  • 1
    )) no, my case is different, I saw this topic. – Alexandr Kovalenko Apr 27 '20 at 08:33
  • I run your code. It giving valid output `{"fieldOne":"some data","someObject":{}}` – Vikas Apr 27 '20 at 08:49
  • 1
    I'd like to see {"fieldOne":"some data"} without "someObject":{} ! – Alexandr Kovalenko Apr 27 '20 at 09:36
  • Take a look at [How to JSON serialize null values but not empty values with Jackson?](https://stackoverflow.com/questions/61286232/how-to-json-serialize-null-values-but-not-empty-values-with-jackson) – Michał Ziober Apr 27 '20 at 10:42

1 Answers1

2

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