简体   繁体   中英

Serialize Jackson field in two different ways

I am doing POJO serialization / deserialization using Jackson. Here is a POJO exemple :

public class Pojo {
    public String productId;
    public String name;
}

I have to read the field productId in this JSON :

{"productId":"1","name":"exemple"}

But also in :

{"_id":"1","name":"exemple"}

To make it short, I would like to use the same object to read the field in a JSON file found somewhere and to save the object as this in MongoDB, using productId as the primary key, which has to be named _id . Since I am using Jackson (fasterxml) both to read from the file and to write to the database, I can not find a way to do so, except by creating a new class with the same fields (or inheritance) and fill them one by one. Basically, I would like to find a way to put 2 @JsonProperty annotations on productId .

Works with both strings:

public class Pojo {
    @JsonProperty("_id")
    public String productId;
    public String name;

    @JsonProperty("productId")
    public void setProductId(String id) {
        productId = id;
    }

}

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