@JsonView 简单介绍[z]

时间:2023-03-08 20:17:00

@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只支持一个参数(视图)。
---------------------
作者:isea533
来源:****
原文:https://blog.****.net/isea533/article/details/40428179?utm_source=copy