In situations where you would like to filter properties from getting serialized dynamically per request Jackson provides a way through JsonFilter's
Here is an example code to create a dynamic filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Your custom logic can go here | |
SimpleBeanPropertyFilter theFilter = new SimpleBeanPropertyFilter() { | |
@Override | |
protected boolean include(BeanPropertyWriter writer) { | |
Annotation annotation = writer.getAnnotation(AvailableForInternalClients.class); | |
//Basically if the annotation is defined and the Client is an External client then we dont include the property | |
return annotation == null || clientTypeIdentifier.isInternalClient(); | |
} | |
}; |
FilterProvider filters = new SimpleFilterProvider().addFilter("enableClientBasedFiltering", theFilter);
objectMapper.setFilters(filters);
If the bean is tagged with JsonFilter Annotation example. @JsonFilter("myFilterId") , then Jackson calls the associated filter for evaluation per request
Jackson does throw an exception when filter is not found. You would have to ensure that the bean marked with JsonFilter annotation should have the filter defined in the object mapper in its classpath