Gson - 使用两个不同的键读取值 [英] Gson - Read a value with two different keys
问题描述
在我的 Android 项目中,我有两种类型的响应,其中 响应除了两个键外都是相同的.
In my Android project I have two types of response where both response are identical except two keys.
响应 1
{"fullName":"William Sherlock Scott Holmes","address":"221B Baker Street, London, England, UK","downloads":642,"rating":3,"repos":["https://link1","https://link2","https://link3"]}
响应 2
{"name":"Sherlock","city":"London","downloads":642,"rating":3,"repos":["https://link1","https://link2","https://link3"]}
如果您看到响应,只有两个键名发生了变化 fullName/name 和 address/city
If you see the responses only two key names are changing fullName/name and address/city
我不想为其他响应再创建一个 pojo.我的问题是:是否可以只使用一个 Pojo 来读取两个回复?
I don't want to create one more pojo for other response. My question is: is it possible to use only one Pojo to read both responses?
public class AccountInfo {
private String name;
private String city;
//other objects
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
//other setters and getters
}
任何帮助将不胜感激...
Any help will be appreciated...
推荐答案
您可以使用 @SerializedName 注释:
@SerializedName(value = "name", alternate = {"fullName"})
private String name;
@SerializedName(value = "city", alternate = {"address"})
private String city;
然后可以将任一命名元素放入这样注释的成员中.
Either named element can then be placed into the members that are annotated like this.
更新:@SerializedName
在 2.4 版
UPDATED :
@SerializedName
alternate names when deserializing is added in Version 2.4
这篇关于Gson - 使用两个不同的键读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!