1、项目中使用JSON的第三方架包:jackson-annotations-2.8.0.jar
2、可以将对象的属性返回进行相应的处理 比如格式化时间、密码敏感等属性
如:User.java
1 package com.leecx.pojo; 2 3 import java.util.Date; 4 5 import com.fasterxml.jackson.annotation.JsonFormat; 6 import com.fasterxml.jackson.annotation.JsonIgnore; 7 import com.fasterxml.jackson.annotation.JsonInclude; 8 import com.fasterxml.jackson.annotation.JsonInclude.Include; 9 10 public class User { 11 12 private String name; 13 private Integer age; 14 15 @JsonIgnore 16 private String password; 17 18 @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss a",locale="zh",timezone="GMT+8") 19 private Date birthday; 20 21 @JsonInclude(Include.NON_NULL) 22 private String desc; 23 24 25 public String getPassword() { 26 return password; 27 } 28 public void setPassword(String password) { 29 this.password = password; 30 } 31 public Date getBirthday() { 32 return birthday; 33 } 34 public void setBirthday(Date birthday) { 35 this.birthday = birthday; 36 } 37 public String getDesc() { 38 return desc; 39 } 40 public void setDesc(String desc) { 41 this.desc = desc; 42 } 43 44 45 46 47 public String getName() { 48 return name; 49 } 50 public void setName(String name) { 51 this.name = name; 52 } 53 public Integer getAge() { 54 return age; 55 } 56 public void setAge(Integer age) { 57 this.age = age; 58 } 59 60 61 }
其中:@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss a",locale="zh",timezone="GMT+8") 可以对时间进行格式化设置
@JsonIgnore 可以对敏感数据进行保护
@JsonInclude(Include.NON_NULL) 可以对要求返回的属性为NULL的不进行返回,如果有数据就正常返回等设置
经过上述设置 那么前台得到的JSON串如下:
{"status":200,"msg":"OK","data":{"name":"duanml","age":18,"birthday":"2018-04-10 06:47:58 下午","desc":"Hello Word!"},"ok":null}
上述中的password 属性值由于设置了保护措施,那么前台返回的时候就默认隐藏了