Skip to main content
1 of 2
Mehdi
  • 3.8k
  • 3
  • 38
  • 67

This is a clean utility tool for the above answer :

@GetMapping(value = "/my-url") public @ResponseBody MappingJacksonValue getMyBean() { List<MyBean> myBeans = Service.findAll(); MappingJacksonValue mappingValue = MappingFilterUtils.applyFilter(myBeans, MappingFilterUtils.JsonFilterMode.EXCLUDE_FIELD_MODE, "MyFilterName", "myBiggerObject.mySmallerObject.mySmallestObject"); return mappingValue; } //AND THE UTILITY CLASS public class MappingFilterUtils { public enum JsonFilterMode { INCLUDE_FIELD_MODE, EXCLUDE_FIELD_MODE } public static MappingJacksonValue applyFilter(Object object, final JsonFilterMode mode, final String filterName, final String... fields) { if (fields == null) { throw new IllegalArgumentException("You should pass at least one field"); } return applyFilter(object, mode, filterName, new HashSet<>(Arrays.asList(fields))); } public static MappingJacksonValue applyFilter(Object object, final JsonFilterMode mode, final String filterName, final Set<String> fields) { if (fields == null) { throw new IllegalArgumentException("You should pass at least one field"); } SimpleBeanPropertyFilter filter = null; switch (mode) { case EXCLUDE_FIELD_MODE: filter = SimpleBeanPropertyFilter.serializeAllExcept(fields); break; case INCLUDE_FIELD_MODE: filter = SimpleBeanPropertyFilter.filterOutAllExcept(fields); break; } FilterProvider filters = new SimpleFilterProvider().addFilter(filterName, filter); MappingJacksonValue mapping = new MappingJacksonValue(object); mapping.setFilters(filters); return mapping; } } 
Mehdi
  • 3.8k
  • 3
  • 38
  • 67