I am using spring rest api 4.x. We have a requirement to filter the fields in the response based on the request parameters.
My User object:
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.
In this case I need to return only the fields which are in the request param "fields". JSON output should contain only firstName, lastName.
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.
Please share some ideas.
It appears this is supported in Spring 4.2 as per https://jira.spring.io/browse/SPR-12586 via Jackson
JsonFilter
(though the jira is returning an error at the moment).Use a
ResponseBodyAdvice
in order to change the response before it got written to the HTTP response. InbeforeBodyWrite(...)
method you have access to the currentServerHttpRequest
which you can read thefields
value. Your body advice would look like following:Thanks Ali. It is a great help. Let me implement it today. I will post the result