作者专注于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")