如何过滤从Spring rest Web服务返回的json响应 [英] How to filter the json response returning from spring rest web service
本文介绍了如何过滤从Spring rest Web服务返回的json响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何过滤从Spring rest Web服务返回的json响应。
How to filter the json response returning from spring rest web service.
当使用调用customEvents时,我只需要输出eventId和Event名称。当询问特定事件时,我需要
发送事件的完整细节。
When use call the customEvents i only need to outout the eventId and the Event name only. When Ask for specifc event i need to send the full details of the event.
Class CustomEvent{
long id;
String eventName;
Account createdBy;
Account modifiedBy;
..
}
Class Account{
long id;
String fname;
String lname;
....
}
@Controller
public class CustomEventService
{
@RequestMapping("/customEvents")
public @ResponseBody List<CustomEvent> getCustomEventSummaries() {}
@RequestMapping("/customEvents/{eventId}")
public @ResponseBody CustomEvent getCustomEvent(@PathVariable("eventId") Long eventId) {}
}
我如何实现上述目标?我现在正在使用spring 3.1。 3.1版本中是否支持以上或以后的版本
how can i achieve the above? I'm using spring 3.1 at the moment. Is ther any support in 3.1 version to achieve above or later verion
推荐答案
您可以使用@JsonFilter进行存档。
You can use @JsonFilter to archive.
Pojo:
@JsonFilter("myFilter")
public class User {
....
}
控制器:
public String getUser(
@RequestParam(value="id") String id,
@RequestParam(value="requiredFields",required=false ) String requiredFields
) throws JsonParseException, JsonMappingException, IOException {
//Get User
User user = userService.getUser(id);
//Start
ObjectMapper mapper = new ObjectMapper();
// and then serialize using that filter provider:
String json="";
try {
if (requiredFields!= null) {
String[] fields = requiredFields.split("\\,");
FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter",
SimpleBeanPropertyFilter.filterOutAllExcept(new HashSet<String>(Arrays
.asList(fields))));
json = mapper.filteredWriter(filters).writeValueAsString(user);//Deprecated
} else {
SimpleFilterProvider fp = new SimpleFilterProvider().setFailOnUnknownId(false);
mapper.setFilters(fp);
json =mapper.writeValueAsString(user);
}
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
获取网址:.....& requiredFields = id,Name,年龄
Get URL: .....&requiredFields=id,Name,Age
这篇关于如何过滤从Spring rest Web服务返回的json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文