@JsonView 简单介绍

@JsonView是jackson json中的一个注解,Spring webmvc也支持这个注解。


这个注解的作用就是控制输入输出后的json.

假设我们有一个用户类,其中包含用户名和密码,一般情况下如果我们需要序列化用户类时,密码也会被序列化,在一般情况下我们肯定不想见到这样的情况。但是也有一些情况我们需要把密码序列化,如何解决这两种不同的情况呢?


使用@JsonView就可以解决。


看下面的简单例子:  

public class User {
    public interface WithoutPasswordView {};
    public interface WithPasswordView extends WithoutPasswordView {};

    private String username;
    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @JsonView(WithoutPasswordView.class)
    public String getUsername() {
        return this.username;
    }

    @JsonView(WithPasswordView.class)
    public String getPassword() {
        return this.password;
    }
}


有这样一个简单的User对象,包含两个简单的属性。


在这个对象中定义了两个接口,其中WithoutPasswordView指的就是不带密码的视图,WithPasswordView指的是带密码的视图,并且继承了WithoutPasswordView的视图。


@JsonView 中的这个视图不仅可以用接口,也可以是一般的类,或者说只要有Class属性就能当成视图使用。


类或接口间的继承,也是视图之间的继承,继承后的视图会包含上级视图注解的方法。


@JsonView 可以写到方法上或者字段上。


下面通过代码测试上面的User对象:  

public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    //创建对象
    User user = new User("isea533","123456");
    //序列化
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    objectMapper.writerWithView(User.WithoutPasswordView.class).writeValue(bos, user);
    System.out.println(bos.toString());

    bos.reset();
    objectMapper.writerWithView(User.WithPasswordView.class).writeValue(bos, user);
    System.out.println(bos.toString());
}

先创建一个objectMapper,然后通过writerWithView工厂方法创建一个指定视图的ObjectWritter,然后通过writeValue输出结果。


输出结果:

{"username":"isea533"}
{"username":"isea533","password":"123456"}

@JsonView 使用起来就是这么简单,没有太复杂的东西。


@JsonView 属性可以写在注解上,这点不知道是否类似Spring中的自定义注解,如果有了解的人可以留言,谢谢。


另外在Spring-webmvc中使用@JsonView 时要注意,虽然该注解允许指定多个视图,但是spring-webmvc只支持一个参数(视图)。



评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

isea533

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值