Reputation: 1051
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"}
Upvotes: 2
Views: 10785
Reputation: 894
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
Upvotes: 2