响应中的Spring Rest API过滤器字段

编程入门 行业动态 更新时间:2024-10-09 11:16:41
本文介绍了响应中的Spring Rest API过滤器字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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过滤器字段

本文发布于:2023-10-12 04:15:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483699.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   过滤器   Spring   Rest   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!