SpringBoot中Jackson的过滤使用

 

在接口的返回对象中,可能会有一些属性为null或者需要禁止某些字段返回给客户端。

在SpringBoot中可使用内置了Jackson实现这个需求

1. 过滤为null字段

在实体类中使用@JsonInclude(JsonInclude.Include.NON_EMPTY)即可过滤调为null的字段

 1 @Data
 2 @JsonInclude(JsonInclude.Include.NON_EMPTY)
 3 public class UserMessageVo {
 4 
 5     /**
 6      * 发送方信息
 7      */
 8     private UserDetail sendUserInfo;
 9 
10     /**
11      * 接收方信息
12      */
13     private UserDetail receiveUserInfo;
14 
15     /**
16      * 发送信息
17      */
18     private String message;
19 
20     /**
21      * 发送时间
22      */
23     private Long createTime;
24 
25     /**
26      * 发送方id
27      */
28     private Integer sendId;
29 
30     /**
31      * 接收方id
32      */
33     private Integer receiverId;
34 
35     /**
36      * 发布事件类型  1: 触发用户聊天记录保存redis事件  2:触发聊天记录保存数据库
37      */
38     private Integer type;
39 
40     /**
41      * 聊天记录
42      */
43     private List<LittleMessageHistory> historyList;
44 
45 }
View Code

2. 过滤指定字段

在实体类上使用@JsonIgnoreProperties(value = {"password"})即可,value可添加多个字段,逗号分割。

 1 @Data
 2 @JsonIgnoreProperties(value = {"password"})
 3 public class UserDetail {
 4 
 5     private static final long serialVersionUID = 1L;
 6 
 7     /**
 8      * 用户id
 9      */
10     private Integer id;
11 
12     /**
13      * 用户名
14      */
15     private String username;
16 
17     /**
18      * 密码
19      */
20     private String password;
21 
22     /**
23      * 昵称
24      */
25     private String nickname;
26 
27     /**
28      * 手机号
29      */
30     private String phone;
31 
32     /**
33      * 邮箱
34      */
35     private String email;
36 
37     /**
38      * 状态 0-->禁用  1-->启用
39      */
40     private Integer status;
41 
42     /**
43      * 性别 -1-->未知  0-->女 1-->男
44      */
45     private Integer gender;
46 
47     /**
48      * 个性签名
49      */
50     private String signature;
51 
52     /**
53      * 用户来源 0-->小程序登录 1-->手机号登录
54      */
55     private Integer source;
56 }
View Code

3. 客户端返回效果

 

posted @ 2021-07-14 11:31  EchoLv  阅读(482)  评论(0编辑  收藏  举报