简体   繁体   中英

Make @SerializedName in Java to work only when deserializing but not serializing

Is there some way to in the class, that a value will be obtained from jsonField1 BUT when being sent out, it should be sent out as jsonField2 .

Incoming json
{
    "name":"john",
    "gender":"female"
 }

Outgoing json
{
    "firstname":"john",
    "gender":"female"
}

The name of the database field is firstname .

I am assuming you are talking about Gson here, but you didn't mention that. Unless you want to write your own TypeAdapter you will need to use two different Gson instances, one for serializing and one for deserializing. For the one where the field name needs to differ you can register a FieldNamingStrategy using GsonBuilder#setFieldNamingStrategy . This interface allows you to remap field names.

I haven't tried it personally but this might work -

@JsonProperty(value="name",access=Access.READ_ONLY)
public void setName(String name){
  this.name = name;
}

@JsonProperty(value="firstname",access=Access.WRITE_ONLY)
public void getName(){
  return name;
}

If the above does not work, you could have two properties, incoming property annotated with Access.READ_ONLY and for outgoing have the property annotated with Access.WRITE_ONLY . However your BO or getter/setter need to deal with both the properties.

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