简体   繁体   中英

Rename field only on Serialization in java

I have an object named AddOnsSRO.Only on serialization I want the names of fields of the object to be changed.

Tried using @JsonProperty on getter methods but it gives me a renamed field even on usages where serialization is not involved.

public class AddOnsSRO {

    private String sideCar;
    private String sideCarCoverage;

    @JsonSerialize
    @JsonProperty("abc")
    public String getSideCar() {
        return sideCar;
    }

    public void setSideCar(String sideCar) {
        this.sideCar = sideCar;
    }

    @JsonSerialize
    @JsonProperty("xyz")
    public String getSideCarCoverage() {
        return sideCarCoverage;
    }

    public void setSideCarCoverage(String sideCarCoverage) {
        this.sideCarCoverage = sideCarCoverage;
    }
}

Only on serialization the following fields : sideCar and sideCarCoverage must be renamed to abc and xyz respectively.

For any other use except serialization the field names should be sideCar and sideCarCoverage only.

Please help and suggest changes or annotations accordingly.

For effecting only serializing use @JsonGetter instead of @JsonProperty

@JsonGetter("abc")
public String getSideCar() {
    return sideCar;
}

Getter means that when serializing Object instance of class that has this method (possibly inherited from a super class), a call is made through the method, and return value will be serialized as value of the property.

You can add @JsonSetter to setter method for deserialize:

@JsonSetter("sideCar")
public void setSideCar(String sideCar) {
    this.sideCar = sideCar;
}

您的代码看起来不错...请升级杰克逊库...如果您使用的是旧版本

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM