【问题标题】:Parsing json into a nested ArrayList in libgdx将 json 解析为 libgdx 中的嵌套 ArrayList
【发布时间】:2015-08-27 11:13:12
【问题描述】:

我使用 Jackson 进行所有的 json 序列化和反序列化,但我现在正试图让我的游戏与 GWT 一起工作,因此我将转向 libgdx json 解析库。

到目前为止一切都很好,除了这个

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

hashmap 中的 ArrayList 被创建为 JsonValue 数组,而不是 HighScoreEntry 数组。

谁能解释我如何解决这个问题?我知道 json.setElementType();但在这种情况下看不到如何使用它。我正在编写自定义序列化,但同样,我无法弄清楚如何准确提取我需要的内容。

我猜我可以使用自定义序列化器

    json.readFields(this, jsonData);

填充所有内容,然后更正错误的数据。

HighScoreEntry 类(无方法):

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;
}

指针将不胜感激。

【问题讨论】:

  • 请提供更多关于HighScoreEntry类的信息
  • @Tukajo 添加了 HighScoreEntry。
  • 什么告诉你它是JsonValue而不是HighScoreEntry
  • @Tukajo 在运行时检查。请看我刚刚添加的图片。
  • 我认为这不是指ArrayList?我相信上面的条目是什么?在您的图像中的Value 下。类型为Array

标签: java json libgdx


【解决方案1】:

我已经解决了一些问题,但我觉得必须有更好的方法。如果其他人有任何想法,请发表。

添加一个自定义阅读器,我可以更正损坏的高分并将它们转换为 HighScoreEntry 对象的实例。

@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>> {

}

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2015-04-11
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多