gpt4 book ai didi

java - 如何在序列化期间忽略字段,但在反序列化期间不忽略?

转载 作者:行者123 更新时间:2023-12-04 21:29:40 24 4
gpt4 key购买 nike

我有一个 POJO 类

class Human{
String name;
Integer age;
//get and set
}

当我将 json 反序列化为 Human 对象时,我想读取两个字段(agename 值)。但是当我将 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;
}

关于java - 如何在序列化期间忽略字段,但在反序列化期间不忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31727966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com