我正在尝试使用本地化反序列化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个字段并检查相关内容是否为空。
另一个非常丑陋的解决方案是每小时编写一个完整的自定义反序列化器,但每小时有大量(超过30个)简单的字符串字段,因此为它编写自定义反序列化器效率似乎效率低,并且违背了GSON的简单性。
是否有更好的简洁解决方案只为lang对象编写自定义反序列化器,并允许GSON自动反序列化其余数据?
答案 0 :(得分:0)
我有一个类似的问题,其中用户对象可以有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;
}
}
}