在球场上的JsonIgnore和在杰克逊球场上的JsonIgnore有什么不同?
发布于 2018-07-24 05:37:35
@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.的批注一起使用时,仅从反序列化中排除属性
发布于 2018-07-24 05:52:46
据我所知,两者之间没有区别。@JsonIgnore JavaDocs似乎使用了各种地方,您也可以将其互换放置。
但是,如果您有不会产生副作用的getter,并且希望最终出于某种原因将像lombok这样的东西合并到您的项目中,那么如果您将@JsonIgnore放在字段中,那么进行转换会容易得多。此外,在IMO中,将这种反/序列化信息放在定义参数的相同位置,即字段本身,会更清楚。
https://stackoverflow.com/questions/51487187
复制相似问题