你怎么能在序列化期间忽略一个字段而不是在反序列化期间?
How can you ignore a field during serialization but not during deserialization?
我有一个 POJO class
class Human{
String name;
Integer age;
//get and set
}
当我将 json 反序列化为 Human
对象时,我想读取两个字段(age
和 name
值)。但是当我将 Human
对象序列化为 json 时,我想忽略 age
.
这可能吗?
@JsonIgnore
的 javadoc 指出
In addition, starting with Jackson 1.9, if this is the only annotation
associated with a property, it will also cause cause the whole
property to be ignored: that is, if setter has this annotation and
getter has no annotations, getter is also effectively ignored. It is
still possible for different accessors to use different annotations;
so if only "getter" is to be ignored, other accessors (setter or
field) would need explicit annotation to prevent ignoral (usually
JsonProperty).
所以只需适当地注释 getter 和 setter
// for serialization
@JsonIgnore
public String getName() {
return name;
}
// for deserialization
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
我有一个 POJO class
class Human{
String name;
Integer age;
//get and set
}
当我将 json 反序列化为 Human
对象时,我想读取两个字段(age
和 name
值)。但是当我将 Human
对象序列化为 json 时,我想忽略 age
.
这可能吗?
@JsonIgnore
的 javadoc 指出
In addition, starting with Jackson 1.9, if this is the only annotation associated with a property, it will also cause cause the whole property to be ignored: that is, if setter has this annotation and getter has no annotations, getter is also effectively ignored. It is still possible for different accessors to use different annotations; so if only "getter" is to be ignored, other accessors (setter or field) would need explicit annotation to prevent ignoral (usually JsonProperty).
所以只需适当地注释 getter 和 setter
// for serialization
@JsonIgnore
public String getName() {
return name;
}
// for deserialization
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}