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
I was having similar requirement for my existing project. It was a pain to introduce views as a single object is used by multiple controllers. It was not a clean solution to implement filter either. So I have decided to clear those values from my DTO in Controller before sending it to the client. So my own couple of methods (which may take bit of more execution time) to address the issue.
public static void includeFields(Object object, String... includeFields) {
for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(object)) {
if (!Arrays.asList(includeFields).contains(propertyDescriptor.getName())) {
clearValues(object, propertyDescriptor);
}
}
}
public static void excludeFields(Object object, String... includeFields) {
for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(object)) {
if (Arrays.asList(includeFields).contains(propertyDescriptor.getName())) {
clearValues(object, propertyDescriptor);
}
}
}
private static void clearValues(Object object, PropertyDescriptor propertyDescriptor) {
try {
if(propertyDescriptor.getPropertyType().equals(boolean.class)) {
PropertyUtils.setProperty(object, propertyDescriptor.getName(), false);
} else {
PropertyUtils.setProperty(object, propertyDescriptor.getName(), null);
}
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
//TODO
e.printStackTrace();
}
}
Drawback is the boolean
fields that will always have value and hence will be present in the payload. At least this helped me give dynamic solution and reduce many fields in the payload.