相关疑难解决方法(0)

如何动态切换 JsonView (Spring MVC/Jackson Mapper)

对于我正在处理的要求,请参阅测试用例中的 de-ignore Json 字段

作为在测试用例中忽略 Json 字段的解决方案,我使用 if else 条件动态切换 json 视图,如下所示。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;

@Component
public class JacksonMapperUtil {

    @Autowired
    private MappingJackson2HttpMessageConverter jsonConverter;

    public void modifyView(final Boolean internalView) {

        if (internalView) {
            this.jsonConverter.getObjectMapper().setConfig (
                    this.jsonConverter.getObjectMapper().getSerializationConfig().withView(View.Internal.class));
        }
        else {
            this.jsonConverter.getObjectMapper().setConfig (
                    this.jsonConverter.getObjectMapper().getSerializationConfig().withView(View.Public.class));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但理论上,当同时有多个请求,其中一个请求需要使用公共视图而其他内部视图需要使用时,这应该不起作用,因为我们正在更新同一对象中的视图。因此,我正在寻找一种解决方案,可以为每个请求动态切换视图。请指出我正确的方向。

spring-mvc jackson json-view

5
推荐指数
0
解决办法
2306
查看次数

在Spring MVC Controller中选择JsonView

我目前正在使用Jackson(2.4.0-rc3)和spring mvc(4.0.3)编写REST api,我正在尝试使其安全.

通过这种方式,我尝试使用JsonView来选择可以序列化的对象部分.

我找到了解决方案(不适合我)用我想要的视图注释我的Controller方法.但我想动态选择控制器内部的视图.

是否可以扩展ResponseEntity类以指定我想要的JsonView?

一小段代码:

这是帐户类

public class Account {

    @JsonProperty(value = "account_id")
    private Long accountId;

    @JsonProperty(value = "mail_address")
    private String mailAddress;

    @JsonProperty(value = "password")
    private String password;

    @JsonProperty(value = "insert_event")
    private Date insertEvent;

    @JsonProperty(value = "update_event")
    private Date updateEvent;

    @JsonProperty(value = "delete_event")
    private Date deleteEvent;

    @JsonView(value = PublicView.class)
    public Long getAccountId() {
        return accountId;
    }

    @JsonView(value = PublicView.class)
    public void setAccountId(Long accountId) {
        this.accountId = accountId;
    }

    @JsonView(value = OwnerView.class)
    public String getMailAddress() {
        return mailAddress;
    } …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc jackson

3
推荐指数
3
解决办法
6203
查看次数

标签 统计

jackson ×2

spring-mvc ×2

java ×1

json-view ×1

spring ×1