zoukankan      html  css  js  c++  java
  • spring boot 之@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只支持一个参数(视图)。

  • 相关阅读:
    Math.pow
    css3正方体
    制作一个百度换肤效果
    排他思想
    js栈和堆的区别
    js创建对象的几种方式(工厂模式、构造函数模式、原型模式)
    短网址
    this
    作用域
    JS 函数基础
  • 原文地址:https://www.cnblogs.com/azhqiang/p/5856832.html
Copyright © 2011-2022 走看看