- Given the model annotated with @JsonInclude annotation.
- Sometime the model objects are in third party jars or libraries, so we can not change the include types specified in @JsonInclude annotations.
- We would to like customize the behavior using ObjectMapper in contextResolver by configuring the Serialization
- It is kind of global serialization for application.
Program – JsonInclude properties ObjectMapper ContextResolver
EmployeeModel Class has annotation @JsonInclude(JsonInclude.Include. NON_NULL)
package org.learn; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) public class EmployeeModel { public String firstName; public String lastName; public int age; public List vehicleList; public EmployeeModel() { vehicleList = new ArrayList<>(); } public EmployeeModel(String firstName, String lastName, int age, List vehicleList) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.vehicleList = vehicleList; } }
default JSON serialization of employee model object
{ firstName: "Random First Name 91cf", lastName: "Random Last Name 9114", age: 35, vehicleList: [ ] }
We can see the empty vehicleList is getting serialized, We can avoid empty list serialization by overriding the behavior of @JsonInclude annotation using ObjectMapper (in ContextResolver).
package org.learn; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @Provider public class ObjectMapperContextResolver implements ContextResolver { private final ObjectMapper objectMapper = new ObjectMapper(); public ObjectMapperContextResolver() { objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS,false); } @Override public ObjectMapper getContext(Class<?> type) { return objectMapper; } }
Output – JsonInclude properties ObjectMapper ContextResolver
The after configuring Serialization feature, the JSON serialization of above model object will be.
{ firstName: "Random First Name 1472", lastName: "Random Last Name 9911", age: 36 }