我有一个返回以下格式的json对象的响应:
{
"playerId": "001",
"name": "michel",
"age": 21,
"nation": "USA",
"ratings": [
{
"type": "speed",
"score": "0121"
},
{
"type": "accuracy",
"score": "85"
}
],
"teaminfo": {
"teamName": "HON",
"isValid": "true"
}
}
并且我有一个Java类:
public class MyRider {
public String playerId;
public String name;
public int age;
public String speed;
public String accuracy;
public String teamName;
public String isValid;
//getter, setter...
}
我想使用GSON将JSON对象映射到Java对象。
我尝试使用JsonDeserializationContext
反序列化,并且它为JSON中的嵌套值返回了null
。
答案 0 :(得分:2)
如果您无法更改JSON以完全返回所需的内容,建议您创建与之匹配的类:
MyRider:
public class MyRider {
private String playerId;
private String name;
private int age;
private String nation;
private List<Rating> ratings;
private TeamInfo teaminfo;
// getters, setters, toString override
}
评分:
public class Rating {
private String type;
private String score;
// getters, setters, toString override
}
TeamInfo:
private static class TeamInfo {
private String teamName;
private String isValid;
// getters, setters, toString override
}
然后简单地按常规反序列化:
MyRider rider = gson.fromJson(json, MyRider.class);
如果您确实需要在问题中的MyRider中指定的字段,请考虑使用转换器类将上面的完整类映射到您的需求。
也可以使用自定义解串器来执行此操作,但是由于GSON为您提供了可以进行调整的法线映射,因此一点意义也没有。
以下是反序列化器的示例:
public class MyRiderDeserializer implements JsonDeserializer<MyRider> {
@Override
public MyRider deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
MyRider rider = new MyRider();
if(json.isJsonObject()) {
JsonObject riderObj = json.getAsJsonObject();
rider.setPlayerId(riderObj.get("playerId").getAsString());
rider.setName(riderObj.get("name").getAsString());
rider.setAge(riderObj.get("age").getAsInt());
JsonArray ratingsArray = riderObj.get("ratings").getAsJsonArray();
for(JsonElement ratingElem : ratingsArray) {
JsonObject ratingObj = ratingElem.getAsJsonObject();
String type = ratingObj.get("type").getAsString();
switch(type) {
case "speed":
rider.setSpeed(ratingObj.get("score").getAsString());
break;
case "accuracy":
rider.setAccuracy(ratingObj.get("score").getAsString());
break;
default:
break;
}
}
JsonObject teamInfo = riderObj.get("teaminfo").getAsJsonObject();
rider.setTeamName(teamInfo.get("teamName").getAsString());
rider.setIsValid(teamInfo.get("isValid").getAsString());
}
return rider;
}
}
请注意,这不包括验证属性是否确实存在的任何检查,并且是我想到的最简单的自定义解串器。要使用它,必须在创建Gson
时注册类型适配器:
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyRider.class, new MyRiderDeserializer())
.create();
MyRider myRider = gson.fromJson(reader, MyRider.class);