我正在使用Spring Rest API4.x.我们需要根据请求参数过滤响应中的字段.
I am using spring rest api 4.x. We have a requirement to filter the fields in the response based on the request parameters.
我的用户对象:
private class UserResource { private String userLastName; private String userFirstName; private String email; private String streetAddress; } E.g. URL: curl -i hostname:port/api/v1/users?fields=firstName,lastName.在这种情况下,我只需要返回请求参数"fields"中的字段. JSON输出应仅包含firstName,lastName.
In this case I need to return only the fields which are in the request param "fields". JSON output should contain only firstName, lastName.
有几种方法可以根据对象过滤Jackson中的字段.就我而言,我需要通过将字段列表传递给Jackson序列化程序来动态过滤.
There are several ways filter the fields in Jackson based on the object. In my case I need to filter dynamically by passing the list of fields to Jackson serializer.
请分享一些想法.
推荐答案感谢阿里.这是一个很大的帮助.让我今天实现它.我将发布结果
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 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; }更多推荐
响应中的Spring Rest API过滤器字段
发布评论