經常使用的json框架有阿里的fastjson 谷歌gson 等,從性能上來講 javabean序列化爲json : jackson > fastjson > gson > json-libjava
這裏介紹幾種jackson經常使用的一些註解:web
指定字段不返回:@JsonIgnorespring
指定日期格式:@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")json
空字段不返回:@JsonInclude(JsonInclude.Include.NON_NULL)app
指定別名:@JsonProperty("othername")框架
1.首先寫個實體類:性能
1 package com.aytsh.demostream; 2 3 import java.util.Date; 4 5 public class User { 6 7 8 private String name; 9 10 11 private int age; 12 13 14 private String phone; 15 16 17 private Date birthDay; 18 19 public String getName() { 20 return name; 21 } 22 23 public void setName(String name) { 24 this.name = name; 25 } 26 27 public int getAge() { 28 return age; 29 } 30 31 public void setAge(int age) { 32 this.age = age; 33 } 34 35 public String getPhone() { 36 return phone; 37 } 38 39 public void setPhone(String phone) { 40 this.phone = phone; 41 } 42 43 public Date getBirthDay() { 44 return birthDay; 45 } 46 47 public void setBirthDay(Date birthDay) { 48 this.birthDay = birthDay; 49 } 50 51 public User(String name, int age, String phone, Date birthDay) { 52 this.name = name; 53 this.age = age; 54 this.phone = phone; 55 this.birthDay = birthDay; 56 } 57 }
而後,寫個controller測試
1 package com.aytsh.demostream.controller; 2 3 import com.aytsh.demostream.User; 4 import org.springframework.web.bind.annotation.GetMapping; 5 import org.springframework.web.bind.annotation.RestController; 6 7 import java.util.Date; 8 9 @RestController 10 public class GetController { 11 12 @GetMapping("/v2/test_json") 13 public Object testJson(){ 14 return new User("hello",12,"119",new Date()); 15 } 16 17 }
作個測試先:this
如今但願達到以下目的:spa
修改User類:
package com.aytsh.demostream; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; public class User{ @JsonInclude(JsonInclude.Include.NON_NULL) private String name; @JsonIgnore private int age; @JsonProperty("mobile") private String phone; @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss",locale = "zh",timezone = "GMT+8") private Date birthDay; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public User(String name, int age, String phone, Date birthDay) { // this.name = name; this.age = age; this.phone = phone; this.birthDay = birthDay; } }
從新測試: