限制REST API的JSON响应中的字段? [英] Limiting Fields in JSON Response for REST API?

查看:115
本文介绍了限制REST API的JSON响应中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring和Java并实现基于REST的服务.我有一组开发人员,他们也为移动设备,iPad和Web进行开发.考虑我有一个豆子

I am using Spring and Java and implementing REST Based services. I have a set of developers who develop for mobile,iPad and Web too. Consider I have a bean

Class User{
private String Name;
private Integer id;
private String photoURL;
private ArrayList<String> ProjectName;
private ArrayList<String> TechnologyList;
private ArrayList<String> InterestList;

//Getters and setters

}

虽然Web开发人员需要整个领域,而移动开发人员只需要其中的两个领域,而iPad需要在移动和Web之间进行一些操作.

While the Web Developers need the entire fields and mobile developers just require two fields from it whereas the iPad requires something in between mobile and web.

由于我使用杰克逊作为解析器,因此有一种方法可以在向控制器请求时指定我需要的所有数据,并避免其他数据.例如,考虑我做一个GET请求,如

Since I am using jackson as a parser, is there a way where while requesting to the controller I can specify which all data I require and avoid the others. For example consider I do a GET request like

GET>http://somedomain.com/users?filter=name,id,photoUrl

哪个返回给我一个类似

{
"name":"My Name",
"id":32434,
"photoUrl":"/sss/photo.jpg"
}

如果有人要求更多字段,则可以将其过滤.请让我知道如何做到这一点,以使我的API保持通用并可供所有人使用.

Sameway if someone asks for some more fields, they could be filtered. Please let me know how this can be done so that my API remains generic and useable for all.

推荐答案

您可以实现所需的功能,但需要做一些额外的工作.我可以为您提供两种解决方案.

You can achieve what you want but some extra work is necessary. I can offer you two solutions.

只需将请求的每个属性放入地图中.

Simply put every property that is requested into the map.

Jackson允许您设置过滤器,以指定要序列化或忽略的属性.

Jackson lets you set filters that specify which properties are serialized or ignored.

FilterProvider filter = new SimpleFilterProvider().addFilter("myFilter",
   SimpleBeanPropertyFilter.filterOutAllExcept(requestedProperties));

String json = objectMapper.writer(filter).writeValueAsString(value);

然后您可以直接返回JSON字符串而不是对象.

You can then return the JSON string directly instead of an object.

对于两种解决方案,理想情况下,您都需要编写一个可以完成此任务的类.但是,如果这样做,您也可以编写自己的消息转换器.例如,您可以扩展MappingJackson2HttpMessageConverter并覆盖writeInternal方法以适合您的需求.这具有很大的优势,您无需更改控制器.

For both solutions you would ideally write a class that does the job. But if you do that you could as well write your own message converter. You could extend the MappingJackson2HttpMessageConverter, for instance, and overwrite the writeInternal method to suit your needs. That has the big advantage that you don't need to change your controllers.

这篇关于限制REST API的JSON响应中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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