0

有什么方法可以@JsonView为整个 Spring MVC 休息控制器声明吗?

我知道我可以声明@JsonView这样的特定方法:

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

但我不想定义@JsonView每个方法,因为我的方法是在超级类中定义的,我不想仅仅为了添加单个注释而重写它们。
我想@JsonView为整个控制器声明,例如:

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

有什么办法可以做到这一点吗?

4

1 回答 1

1

创建将使用预定义视图的自定义对象映射器

public class CustomObjectMapper extends ObjectMapper {

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

将其注册为 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" />
于 2015-09-11T14:40:30.080 回答