作者專注於Java、架構、Linux、小程序、爬蟲、自動化等技術。 工作期間含淚整理出一些資料,微信搜索【程序員高手之路】,回覆 【java】【黑客】【爬蟲】【小程序】【面試】等關鍵字免費獲取資料。技術交流、項目合作可私聊。
前言
本文所寫註解位於com.fasterxml.jackson.annotation包中
依賴:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
java代碼中常常用到jackson的註解,主要用到的有:@JsonProperty、@JsonIgnore、@JsonIgnoreProperties、@JsonFormat
舉例:
實體類Student
@JsonIgnoreProperties(value = { "address", "score" })
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@JsonProperty(value = "name", required = true)
private String trueName;
@JsonIgnore
private int age;
@JsonFormat(timezone = "GTM+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;
private String address;
private String score;
public String getTrueName() {
return trueName;
}
public void setTrueName(String trueName) {
this.trueName = trueName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
@Override
public String toString() {
return "name: " + this.trueName + ", address: " + this.address + ", age:"
+ this.age + ", birthday:" + this.birthday + ", score:" + this.score;
}
}
測試註解:
public class TestJsonProperty {
public static void main(String[] args) throws IOException {
Student student = new Student();
student.setTrueName("張三");
student.setAge(20);
student.setBirthday(new Date());
student.setAddress("上海市");
student.setScore("90");
// 使用writeValuesAsString把對象轉化成json字符串。
String stuJson = new ObjectMapper().writeValueAsString(student);
System.out.println(stuJson);
//使用readValue把字符串轉化爲對象
Student stu = new ObjectMapper().readValue(stuJson, Student.class);
System.out.println(stu.toString());
}
}
結果:
{"birthday":"2020-04-16 03:57:06","name":"張三"}
name: 張三, address: null, age:, birthday:Thu Apr 16 11:57:06 CST 20200, score:null
一、@JsonProperty
寫法有兩種:
第1種:全寫,使用“=”;
@JsonProperty(value = "", required = true)
第2種:簡寫,直接把value寫到括號裏,required默認爲false。
@JsonProperty("")
value屬性:代表該屬性序列化和反序列化的時候的key值。
required屬性:默認false,例如當required=false的時候,當反序列化的時候沒有找到key值,就會報錯。
二、@JsonIgnore
一般標記在屬性或者方法上,返回的json數據即不包含該屬性
三、@JsonIgnoreProperties
類註解,作用是json序列化時將java bean中的一些屬性忽略掉,序列化和反序列化都受影響。
四、@JsonFormat
用於屬性或者方法上(最好是屬性上),可以方便的把Date類型直接轉化爲我們想要的模式
寫法:@JsonFormat(timezone = "GTM+8", pattern = "yyyy-MM-dd HH:mm:ss")