@JsonProperty的使用
jackson的maven依赖
import com.fasterxml.jackson.annotation.JsonProperty;
public class Student {
@JsonProperty("name")
private String trueName;
public String getTrueName() {
return trueName;
}
public void setTrueName(String trueName) {
this.trueName = trueName;
}
}
测试一下
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws JsonProcessingException {
Student student = new Student();
student.setTrueName(“张三”);
System.out.println(new ObjectMapper().writeValueAsString(student));
}
}
得到结果
1
{“name”:“张三”}
这里需要注意的是将对象转换成json字符串使用的方法是fasterxml.jackson提供的!!
@JsonProperty不仅仅是在序列化的时候有用,反序列化的时候也有用,比如有些接口返回的是json字符串,命名又不是标准的驼峰形式,在映射成对象的时候,将类的属性上加上@JsonProperty注解,
里面写上返回的json串对应的名字