[英]Deserializing fields with different names to the same field with GSON
我正在努力通过本地化反序列化World Weather Online API结果。
根据给定语言而以lang-{locale}
块形式返回的本地化数据(WWO支持约40种语言:
"hourly": [
{
"chanceoffog": "0",
"chanceoffrost": "0",
"chanceofhightemp": "0",
"chanceofovercast": "63",
"chanceofrain": "3",
"chanceofremdry": "0",
"chanceofsnow": "0",
"chanceofsunshine": "0",
"chanceofthunder": "0",
"chanceofwindy": "0",
"cloudcover": "88",
"DewPointC": "1",
"DewPointF": "34",
"FeelsLikeC": "4",
"FeelsLikeF": "39",
"HeatIndexC": "7",
"HeatIndexF": "44",
"humidity": "67",
"lang_ru": [
{
"value": "Пасмурно"
}
],
"precipMM": "0.0",
"pressure": "1033",
"tempC": "7",
"tempF": "44",
"time": "24",
"visibility": "10",
"weatherCode": "122",
"weatherDesc": [
{
"value": "Overcast"
}
],
"weatherIconUrl": [
{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png"
}
],
"WindChillC": "4",
"WindChillF": "39",
"winddir16Point": "WNW",
"winddirDegree": "294",
"WindGustKmph": "17",
"WindGustMiles": "11",
"windspeedKmph": "14",
"windspeedMiles": "9"
}
]
也可以是lang_es
, lang_fr
等。
无论给定哪种语言,我都需要使用字符串将其反序列化为一个字段。
我想到的一个难看的解决方案是根据语言添加40个字段,并检查相关字段是否不为null。
另一个非常丑陋的解决方案是每小时编写一个完整的自定义解串器,但是每小时每小时有(超过30个)简单字符串字段的负载,因此编写自定义解串器似乎效率低下并且与GSON的简单性背道而驰。
有没有更好,更简单的解决方案来编写仅用于lang对象的自定义反序列化器,并允许GSON自动反序列化其余数据?
我有一个类似的问题,即用户对象可以具有id,userId或user_id,这就是我设法将它们全部三个映射到id的方式。
public class UserDeserializer implements JsonDeserializer<User> {
@Override
public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
User user = new GsonBuilder().create().fromJson(json, User.class);
if (user.id == null) {
JsonObject jsonObject = json.getAsJsonObject();
JsonElement userId = jsonObject.get("userid");
if (userId != null) {
user.id = userId.getAsString();
return user;
}
JsonElement user_id = jsonObject.get("user_id");
if (user_id != null) {
user.id = user_id.getAsString();
return user;
}
}
return user;
} catch (JsonParseException ex) {
ex.printStackTrace();
throw ex;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.