Parsing json into a nested ArrayList in libgdx

守給你的承諾、 提交于 2019-12-25 05:29:10

问题


I was using Jackson for all my json serialisation and deserialisation, but I'm trying to get my game working with GWT now so I'm moving over to the libgdx json parsing libraries.

Everything seems ok so far except this

HashMap<String, ArrayList<HighScoreEntry>> high_scores =
              new HashMap<String, ArrayList<HighScoreEntry>>();

The ArrayList within the hashmap is being created as a array of JsonValue rather than an array of HighScoreEntry.

Can someone explain how I work around this? I know about json.setElementType(); but can't see how to use it in this instance. I'm playing with writing custom serialisation, but again, I can't work out how to extract exactly what I need.

I'm guessing in a custom serialiser I can use

    json.readFields(this, jsonData);

to populate everything and then correct the erroneous data afterwards.

HighScoreEntry class (without methods):

public class HighScoreEntry implements Comparable<HighScoreEntry>, java.io.Serializable {
    public long id;
    public int score;
    public String language = "en";
    public String data;
    public String name;

    public boolean current;
}

Pointers would be appreciated.


回答1:


I've worked something out, but I feel like there must be a better way. If anyone else has any ideas then please post them.

Adding a custom reader I can correct the corrupted high scores and convert them into instances of HighScoreEntry objects.

@Override
public void read(Json json, JsonValue jsonData) {
    // Read all the fields
    json.readFields(this, jsonData);

    // replace high scores
    HighScoreHashMapJsonValue screwedUpHashMap = json.readValue(HighScoreHashMapJsonValue.class, jsonData.get("high_scores"));
    HashMap<String, Array<HighScoreEntry>> newHighScores = new HashMap<String, Array<HighScoreEntry>>();

    for (Map.Entry<String, Array<JsonValue>> entry : screwedUpHashMap.entrySet()) {
        String key = entry.getKey();
        Array<JsonValue> jsonValueHighScores = entry.getValue();

        Array<HighScoreEntry> highScoreArray = new Array<HighScoreEntry>();
        newHighScores.put(key, highScoreArray);
        for (JsonValue highScore : jsonValueHighScores) {
            highScoreArray.add(json.readValue(HighScoreEntry.class, highScore));
        }
    }

    high_scores = newHighScores;
}

public static class HighScoreHashMapJsonValue extends HashMap<String, Array<JsonValue>> {

}


来源:https://stackoverflow.com/questions/30786193/parsing-json-into-a-nested-arraylist-in-libgdx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!