0

Is there some way how I can declare @JsonView for whole Spring MVC rest controller?

I know I can declare @JsonView for particular method like this:

 @RequestMapping(value = "/user", method = RequestMethod.G
 @JsonView(User.WithoutPasswordView.class)
 public User getUser() {
      return new User("eric", "7!jd#h23");
 } 

But I don't want to define @JsonView per method because my methods are defined in supper class and I don't want to override them just to add single annotation.
I would like to declare @JsonView for whole controller i.e. like this:

@RestController
@RequestMapping(ZONES_PATH)
@JsonView(User.WithoutPasswordView.class)
public class ZoneResource extends GenericRestService<Zone> {
     ...

Is there some way I can achieve this?

Ondrej Bozek
  • 10,987
  • 7
  • 54
  • 70
  • You resolved the problem? I'm in the same situation. :) –  Jul 17 '17 at 14:08
  • 1
    I've abandoned `@JsonView`. They are problematic and confusing. It seems cleaner to define specific transfer objects and e.g. use mappers. – Ondrej Bozek Jul 17 '17 at 14:16
  • Can you tell me how I can use mapper for solve this problem? You can recommend me a useful link? Thanks! –  Jul 17 '17 at 14:27
  • You just simply define ne object which is same as the original object, but contains only properties you want to include. Map original object to new object using e.g. MapStruct (http://mapstruct.org/). return that new object. – Ondrej Bozek Jul 17 '17 at 14:41

1 Answers1

1

create custom object mapper that will use pre-defined view

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        super();
        setSerializationConfig(getSerializationConfig()
                .withView(User.WithoutPasswordView.class));
    }
}

register it as default object mapper used by spring

<mvc:annotation-driven>
    <mvc:message-converters>        
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="objectMapper" ref="jacksonObjectMapper" />
        </bean>        
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="jacksonObjectMapper" class="com.web.CustomObjectMapper" />
KSTN
  • 2,002
  • 14
  • 18
  • That is interesting idea, but wouldn't it define `@JsonView` for whole application? I need it scoped only for particular REST Controller. – Ondrej Bozek Sep 12 '15 at 15:49
  • Yes and for the whole Spring MVC controller. You can also do it like this `mapper.writer().withView(User.WithoutPasswordView.class).writeValueAsString(myEntityWithView);`. Annotations cannot be inherited but method can – KSTN Sep 14 '15 at 02:11