Yes, there is a much simpler way to do that using fasterXML annotation.
Create filter using fasterXML, and define the fields you wish to filter. The list of properties can be defined hardcoded, or calculated in runtime.
For example in admin controller the filter list is empty(or partial), and regular controller the filter is list contain values:
The class you are serializing:
@JsonFilter("PersonFilter")
public class Person
{
private List<Integer> integerList;
private Integer creditCardNUmber;
private String firstName;
private String lastName;
public static FilterProvider getFilter(){
Set<String> fieldsToFilter= new HashSet<>(Arrays.asList("creditCardNUmber","integerList");
SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter
.serializeAllExcept(fieldsToFilter);
FilterProvider filters = new SimpleFilterProvider()
.addFilter("PersonFilter", theFilter);
return filters;
}
}
When you serialize the object you can use predefined list of properties to filter (public static FilterProvider getFilter(){..}
), or define them in runtime.
public static String GetObjectAsStringWithFilter(FilterProvider filters, Object jsonObject)
{
if (jsonObject == null)
{
return null;
}
String objectAsString = null;
try
{
objectAsString = objectMapper.writer(filters).writeValueAsString(jsonObject);
}
catch (Exception e)
{
...
}
return objectAsString;
}