响应中的Spring Rest API过滤器字段 [英] Spring rest api filter fields in the response

查看:164
本文介绍了响应中的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 http://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过滤器字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆