介绍
Jackson注解@JsonProperty介绍_疯狂的太阳的博客-CSDN博客_jackson jsonproperty注解
JsonProperty作用于序列化或者反序列化时,映射的属性的名字,可以放在get方法,set方法,属性上,都可以。
@JsonProperty(value = "fullName")
private String name;
序列化后
{"fullName":"zhangsan"}
Access属性
属性值 说明
WRITE_ONLY 仅做反序列化操作
READ_ONLY 仅做序列化操作
@JsonProperty 有一个属性Access,用来控制是否 能被【序列化】或者【反序列化】,默认是不受控制的。
属性值READ_ONLY
只能序列化,不能反序列化。
@JsonProperty(value = "fullName")
private String name;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String password;
序列化后
{"password":"123456","fullName":"zhangsan"}
属性值WRITE_ONLY
仅做反序列化操作
@JsonProperty(value = "fullName")
private String name;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
序列化后
{"fullName":"zhangsan"}
例子代码
建个实体类
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
public class TestSerializable implements Serializable {
private static final long serialVersionUID = 1L;
@JsonProperty(value = "fullName")
private String name;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public static void main(String[] args) throws Exception {
TestSerializable test = new TestSerializable();
test.setPassword("123456");
test.setName("zhangsan");
//使用writeValuesAsString的方法转化成json字符串。
System.out.println(new ObjectMapper().writeValueAsString(test));
}