使用GSON将JSON对象转换为具有不同格式的Java对象

我有一个返回以下格式的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.

解决方法:

没有自定义解串器

如果您无法更改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);
上一篇:java-为什么gson不序列化此教程代码?


下一篇:java-是否需要严格定义JSON值类型?