【问题标题】:@JsonView declaration for whole Spring MVC rest controler整个 Spring MVC 休息控制器的 @JsonView 声明
【发布时间】:2015-12-06 10:33:06
【问题描述】:

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

我知道我可以为这样的特定方法声明@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> {
     ...

有什么方法可以实现吗?

【问题讨论】:

  • 您解决了问题?我也有同样的情况。 :)
  • 我已经放弃了@JsonView。它们是有问题且令人困惑的。定义特定的传输对象似乎更清晰,例如使用映射器。
  • 你能告诉我如何使用 mapper 来解决这个问题吗?你可以给我推荐一个有用的链接吗?谢谢!
  • 您只需定义一个与原始对象相同的对象,但只包含您想要包含的属性。使用例如将原始对象映射到新对象MapStruct (mapstruct.org)。返回那个新对象。

标签: java json spring-mvc jackson json-view


【解决方案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" />

【讨论】:

  • 这是一个有趣的想法,但它不会为整个应用程序定义@JsonView 吗?我需要它只适用于特定的 REST 控制器。
  • 是的,对于整个 Spring MVC 控制器。你也可以这样做mapper.writer().withView(User.WithoutPasswordView.class).writeValueAsString(myEntityWithView);。注解不能被继承,但方法可以
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 2018-01-17
  • 1970-01-01
  • 2018-07-31
  • 2017-08-15
相关资源
最近更新 更多