Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring rest api filter fields in the response

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.

like image 266
Raj Avatar asked Feb 02 '16 15:02

Raj


1 Answers

Thanks Ali. It is a great help. Let me implement it today. I will post the result

@JsonFilter("blah.my.UserEntity")
public class UserEntity implements Serializable {
//fields goes here
}

@RequestMapping(value = "/users", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public MappingJacksonValue getUsers(@RequestParam MultiValueMap<String, String> params) {
//Build pageable here
Page<UserEntity> users = userService.findAll(pageable);

    MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(users);
    FilterProvider filters = new SimpleFilterProvider()
                .addFilter("blah.my.UserEntity", SimpleBeanPropertyFilter
                        .filterOutAllExcept("userFirstName"));
    mappingJacksonValue.setFilters(filters);
    return mappingJacksonValue;
}
like image 75
Raj Avatar answered Sep 17 '22 13:09

Raj