问题
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