Select JsonView in the Spring MVC Controller

前端 未结 4 1398
故里飘歌
故里飘歌 2020-12-25 09:10

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

4条回答
  •  独厮守ぢ
    2020-12-25 10:01

    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
    

提交回复
热议问题