I\'m currently writing a REST api using Jackson (2.4.0-rc3) and spring mvc (4.0.3), and I\'m trying to make it secure.
In this way, I try to use JsonView to select
I really like the solution presented here to dynamically select a json view inside your controller method.
Basically, you return a MappingJacksonValue
which you construct with the value you want to return. After that you call setSerializationView(viewClass)
with the proper view class. In my use case, I returned a different view depending on the current user, something like this:
@RequestMapping("/foos")
public MappingJacksonValue getFoo(@AuthenticationPrincipal UserDetails userDetails ) {
MappingJacksonValue value = new MappingJacksonValue( fooService.getAll() );
if( userDetails.isAdminUser() ) {
value.setSerializationView( Views.AdminView.class );
} else {
value.setSerializationView( Views.UserView.class );
}
return value;
}
BTW: If you are using Spring Boot, you can control if properties that have no view associated are serialized or not by setting this in your application.properties
:
spring.jackson.mapper.default_view_inclusion=true