简体   繁体   English

如何在序列化期间忽略字段,而不是在反序列化期间忽略?

[英]How can you ignore a field during serialization but not during deserialization?

I have a POJO class 我有一个POJO课程

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

When I deserialize json to a Human object I want to read both fields ( age and name values). 当我将json反序列化为Human对象时,我想要读取两个字段( agename值)。 But when I serialize a Human object to json I want to ignore age . 但是当我将一个Human对象序列化为json时,我想忽略age

Is this possible ? 这可能吗 ?

The javadoc of @JsonIgnore states @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. 另外,从Jackson 1.9开始,如果这是与属性关联的唯一注释,它也会导致整个属性被忽略:也就是说,如果setter有这个注释而getter没有注释,getter也会被忽略。 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或field)将需要显式注释来防止ignoral(通常是JsonProperty)。

So just annotate the getter and setter appropriately 所以只需适当地注释getter和setter

// for serialization
@JsonIgnore 
public String getName() {
    return name;
}
// for deserialization
@JsonProperty("name")
public void setName(String name) {
    this.name = name;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Hibernate中,如何仅在序列化过程中而不在反序列化过程中忽略属性 - In Hibernate how to ignore a property only during serialization and not in deserialization 如果字段值为空,如何告诉杰克逊在序列化期间忽略该字段? - How to tell Jackson to ignore a field during serialization if its value is null? 在序列化和反序列化期间如何调用构造函数? - How are constructors called during serialization and deserialization? 春季反序列化期间忽略字段? - Ignore fields during deserialization in spring? 在反序列化过程中如何获取字段值? - How field values are taken during deserialization in java? 序列化工具如何在反序列化期间跳过未知字段? - How does serialization tool skip unknown fields during deserialization? YAML Mapper 如何在反序列化过程中忽略 yml 文件中的某些字段? - How can YAML Mapper ignore certain fields in the yml file during deserialization? 序列化期间忽略Jackson JsonIdentityInfo - Ignore the Jackson JsonIdentityInfo during serialization 如何在 jackson 反序列化期间忽略 json 数组的类型信息? - How to ignore type information on json arrays during jackson deserialization? 从JSON反序列化期间如何忽略具有空值的属性 - How to ignore properties with empty values during deserialization from JSON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM