简体   繁体   English

使Java中的@SerializedName仅在反序列化而不是序列化时起作用

[英]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 . 类中是否有某种方法,发送时将从jsonField1 BUT获得一个值,它应该作为jsonField2发送出去。

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

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

The name of the database field is firstname . 数据库字段的名称为firstname

I am assuming you are talking about Gson here, but you didn't mention that. 我假设您在这里谈论的是Gson,但您没有提及。 Unless you want to write your own TypeAdapter you will need to use two different Gson instances, one for serializing and one for deserializing. 除非您要编写自己的TypeAdapter ,否则将需要使用两个不同的Gson实例,一个用于序列化,另一个用于反序列化。 For the one where the field name needs to differ you can register a FieldNamingStrategy using GsonBuilder#setFieldNamingStrategy . 对于字段名称需要不同的字段,您可以使用GsonBuilder#setFieldNamingStrategy注册一个FieldNamingStrategy 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 . 如果上述方法不起作用,则可能有两个属性,传入属性以Access.READ_ONLY注释,传出属性以Access.WRITE_ONLY注释。 However your BO or getter/setter need to deal with both the properties. 但是,您的BO或getter / setter需要同时处理这两个属性。

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

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