[英]How to use different field names based on the app version in Gson?
I have a rest API running using Java and Gson and have a task to standardize the names of the fields.我有一个使用 Java 和 Gson 运行的休息 API,并且有一个任务来标准化字段的名称。 Unfortunately, they were created in my native language and now they need to be changed to English.
不幸的是,它们是用我的母语创建的,现在需要更改为英语。 I was thinking in a way where I could support old versions, passing the old field names.
我在想一种可以支持旧版本的方式,传递旧的字段名称。
Is it possible to use the @Since annotation with @SerializedName?是否可以将@Since 注释与@SerializedName 一起使用? Or any solution to change the field names dynamically based in the version?
或者任何基于版本动态更改字段名称的解决方案?
As far as I know, you cannot combine @Since
and @SerializedName
to dynamically change field names.据我所知,你不能结合
@Since
和@SerializedName
来动态更改字段名称。 Another way is to use FieldNamingStrategy
with a variable ver
to determine which name is supposed to be used for serialization.另一种方法是使用带有变量
ver
FieldNamingStrategy
来确定应该使用哪个名称进行序列化。
Following example shows if there is a field named user
in your POJO, then you can change its name with different pre-defined ver
(such as 0.1 or 0.2) for serialization.下面的例子显示,如果有一个字段中指定
user
在你的POJO,那么你就可以改变它的名称不同的预先定义的ver
(如0.1或0.2)进行序列化。
Code Snippet代码片段
double ver = 0.1;
Gson gson = new GsonBuilder()
.setFieldNamingStrategy(new FieldNamingStrategy() {
@Override
public String translateName(Field field) {
if ("user".equals(field.getName())) {
if (ver == 0.1) {
return "username";
} else if (ver == 0.2) {
return "user_name";
} else {
return field.getName();
}
} else {
return field.getName();
}
}
})
.create();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.