Spring leave api filter fields in response

I am using spring rest api 4.x. We have a requirement to filter the fields in the response based on the request parameters.

My User Object:

private class UserResource { private String userLastName; private String userFirstName; private String email; private String streetAddress; } Eg URL: curl -i http://hostname:port/api/v1/users?fields=firstName,lastName. 

In this case, I need to return only the fields that are in the parameters of the "field" of the request. The JSON output should contain only firstName, lastName.

There are several ways to filter fields in Jackson based on an object. In my case, I need to filter dynamically by passing a list of fields to the Jackson serializer.

Please share some ideas.

+5
source share
3 answers

Thanks Ali. This is a big 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 here Page<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; } 
+3
source

Use ResponseBodyAdvice to modify the response before it was written to the HTTP response. In the beforeBodyWrite(...) method, you have access to the current ServerHttpRequest , which you can read with the value of fields . Your body advice will look like this:

 @ControllerAdvice public 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; } } 
+1
source

This seems to be supported in Spring 4.2 at https://jira.spring.io/browse/SPR-12586 via Jackson JsonFilter (although jira is returning an error at the moment).

0
source

Source: https://habr.com/ru/post/1242107/


All Articles