Spring rest api filter fields in the response
Thanks Ali. It is a great help. Let me implement it today. I will post the result
@JsonFilter("blah.my.UserEntity")public class UserEntity implements Serializable {//fields goes here}@RequestMapping(value = "/users", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)public MappingJacksonValue getUsers(@RequestParam MultiValueMap<String, String> params) {//Build pageable herePage<UserEntity> users = userService.findAll(pageable); MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(users); FilterProvider filters = new SimpleFilterProvider() .addFilter("blah.my.UserEntity", SimpleBeanPropertyFilter .filterOutAllExcept("userFirstName")); mappingJacksonValue.setFilters(filters); return mappingJacksonValue;}
Use a ResponseBodyAdvice
in order to change the response before it got written to the HTTP response. In beforeBodyWrite(...)
method you have access to the current ServerHttpRequest
which you can read the fields
value. Your body advice would look like following:
@ControllerAdvicepublic class MyResponseBodyAdvisor implements ResponseBodyAdvice<UserResource> { @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return returnType.getParameterType().equals(UserResource.class); } @Override public UserResource beforeBodyWrite(UserResource body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { String fields = ((ServletServerHttpRequest) request).getServletRequest().getParameter("fields"); // body.set...(null) for each field not in fields return body; }}
It appears this is supported in Spring 4.2 as per https://jira.spring.io/browse/SPR-12586 via Jackson JsonFilter
(though the jira is returning an error at the moment).