How to filter the json response returning from spring rest web service.
When use call the customEvents i only need to outout the eventId and the Event name only. Whe
You can use @JsonFilter to archive.
Pojo:
@JsonFilter("myFilter")
public class User {
....
}
Controller:
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(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;
}
Get URL: .....&requiredFields=id,Name,Age