JsonView用法

@JsonView是jackson json中的一个注解,Spring webmvc也支持这个注解。源码如下:

@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD,
	    ElementType.PARAMETER, // since 2.5
	    ElementType.TYPE // since 2.9, to indicate "default view" for properties
})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonView {
    /**
     * View or views that annotated element is part of. Views are identified
     * by classes, and use expected class inheritance relationship: child
     * views contain all elements parent views have, for example.
     */
    public Class<?>[] value() default { };
}

此注解的主要用途就是当你返回实体类时去除敏感信息。比如:有个user表里面有个pwd字段,查询出user后,不想返回pwd字段。可以使用此注解去除pwd字段。

使用如下:

@Data
public class User {
    
    public interface BaseView{}

    public interface DetailView extends BaseView{}
    
    @JsonView(BaseView.class)
    private String id;
    
    @JsonView(BaseView.class)
    private String name;

    @JsonView(DetailView.class)
    private String pwd;
}

BaseView作为基础视图,DetailView作为详细视图。Detail继承了BaseView,也就是说DetailView会返回所有被@JsonView(BaseView.class)注解了的实例变量。该User实体类中,id和name使用了@JsonView(BaseView.class),pwd使用了@JsonView(DetailView.class)。

在Controller层中的方法上,使用两种视图也是使用JSONView注解。具体如下:

    @GetMapping("getAllUser")
    @ResponseBody
    @JsonView(User.DetailView.class)
    public List<User> getAllUser(){
        List<User> userList = new ArrayList<>();
        User user1 = new User("1", "Cauchy6317", "123456");
        User user2 = new User("2", "CJ", "123456789");
        userList.add(user1);
        userList.add(user2);
        return userList;
    }
使用@JsonView(User.DetailView.class)就会返回所有的实例变量,使用@JsonView(User.BaseView.class)就会id和name。

使用过程中注意一点:实体的所有变量都要被JsonView注解一下,如果上例的pwd没有使用JsonView注解的话,BaseView也会无法使用。

看看源码,@Target中有句ElementType.PARAMETER, // since 2.5,这是放在方法参数上的,具体什么情景下使用,我也没遇到。还有一句ElementType.TYPE // since 2.9, to indicate "default view" for properties,意思是说放在实体类上作为一种默认的视图。比如我们上面的User实体类,在实体类上加上@JsonView(User.BaseView.class),这就是表明凡是返回User的地方如果没有显示指定所需要返回的视图,则默认使用BaseView视图。

有帮助的话,记得点赞关注哈。打赏是对我最大的鼓励!

 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值