SpringBoot(2) Json框架 -- Jackson返回結果處理


一、常用框架 阿里 fastjson,谷歌gson等
JavaBean序列化為Json,性能:Jackson > FastJson > Gson > Json-lib 同個結構
Jackson、FastJson、Gson類庫各有優點,各有自己的專長(空間換時間,時間換空間)

 

二、jackson相關自動處理

指定字段不返回:@JsonIgnore
指定日期格式:@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
空字段不返回:@JsonInclude(Include.NON_NUll)
指定別名:@JsonProperty

 

例如:返回User類

 1    /**
 2      * 功能描述:bean對象傳參
 3      * 注意:1、注意需要指定http頭為 content-type為application/json
 4      *         2、使用body傳輸數據
 5      * @param user
 6      * @return
 7      */
 8     @RequestMapping("/v1/save_user")
 9     public Object saveUser(@RequestBody User user){
10         params.clear();
11         params.put("user", user);
12         return params;    
13     }
14     

User類

 1 public class User {
 2 
 3     private int age;
 4     
 5     @JsonIgnore
 6     private String pwd; //忽略不返回
 7     
 8     @JsonProperty("account") 
 9     @JsonInclude(Include.NON_NULL)
10     private String phone; //別名+為空不返回
11     
12     @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
13     private Date createTime; //時間格式
14 
15     public Date getCreateTime() {
16         return createTime;
17     }
18 
19     public void setCreateTime(Date createTime) {
20         this.createTime = createTime;
21     }
22 
23     public int getAge() {
24         return age;
25     }
26 
27     public void setAge(int age) {
28         this.age = age;
29     }
30 
31     public String getPwd() {
32         return pwd;
33     }
34 
35     public void setPwd(String pwd) {
36         this.pwd = pwd;
37     }
38 
39     public String getPhone() {
40         return phone;
41     }
42 
43     public void setPhone(String phone) {
44         this.phone = phone;
45     }
46 
47     public User() {
48         super();
49     }
50 
51     public User(int age, String pwd, String phone, Date createTime) {
52         super();
53         this.age = age;
54         this.pwd = pwd;
55         this.createTime = createTime;
56     }
57     
58 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM