Field 上的 JsonIgnore
与 Jackson 字段的 getter 上的 JsonIgnore
有什么区别?
最佳答案
@JsonIgnore
注解用于忽略反序列化和序列化的字段,可以直接放在实例成员上,也可以放在它的getter或setter上。在这 3 点中的任何一个中应用注释,都会导致从序列化和反序列化过程中完全排除该属性(这适用于从 Jackson 1.9 开始;这些示例中使用的版本是 Jackson 2.4.3) .
注意:在 1.9 版本之前,这个注解纯粹是在逐个方法(或逐个字段)的基础上工作;一个方法或字段上的注释并不意味着忽略其他方法或字段
例子
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
class MyTestClass {
private long id;
private String name;
private String notInterstingMember;
private int anotherMember;
private int forgetThisField;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public String getNotInterstingMember() {
return this.notInterstingMember;
}
public void setNotInterstingMember(String notInterstingMember) {
this.notInterstingMember = notInterstingMember;
}
public int getAnotherMember() {
return this.anotherMember;
}
public void setAnotherMember(int anotherMember) {
this.anotherMember = anotherMember;
}
public int getForgetThisField() {
return this.forgetThisField;
}
@JsonIgnore
public void setForgetThisField(int forgetThisField) {
this.forgetThisField = forgetThisField;
}
@Override
public String toString() {
return "MyTestClass [" + this.id + " , " + this.name + ", " + this.notInterstingMember + ", " + this.anotherMember + ", " + this.forgetThisField + "]";
}
}
输出:
{"id":1,"name":"Test program","anotherMember":100}
MyTestClass [1 , Test program, null, 100, 0]
但仍然可以更改此行为并使其不对称,例如使用 @JsonIgnore
注释和另一个名为 @JsonProperty 的注释仅从反序列化中排除属性。
关于java - JsonIgnore on Field vs JsonIgnore on getter of Jackson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51487187/