如何将数组添加到首选项 (libGdx)

How to add a array to preferences (libGdx)

您好,我正在尝试获取保存在首选项文件中的整数数组。

    int[] ints = {2, 3, 4};

    Hashtable<String, int[]> hashTable = new Hashtable<String, int[]>();
    hashTable.put("test", ints);

    pref.getPref().put(hashTable);
    pref.getPref().flush();

    Gdx.app.log(String.valueOf(pref.getPref().get()), "");

但是我保存了 0 个首选项。我也用 HashMap 试过了。

Preferences 仅存储 String,因此您可以序列化 Array 或将数组保存为索引和值对,如下所示:

int[] ints = {2, 3, 4};

for (int x = 0; x<ints.length; x++){
   pref.put(Integer.toString(x),Integer.toString(ints[x]));
}

您不能将数组对象放入首选项中,但是您可以使用字符串来做到这一点,因此您只需要在保存之前进行序列化,并在从首选项中获取值后进行反序列化。

Libgdx 通过交付 JSON class 支持序列化。您应该遵循的是:

    Hashtable<String, String> hashTable = new Hashtable<String, String>();

    Json json = new Json();

    hashTable.put("test", json.toJson(ints) ); //here you are serializing the array

    ... //putting the map into preferences

    String serializedInts = Gdx.app.getPreferences("preferences").getString("test");
    int[] deserializedInts = json.fromJson(int[].class, serializedInts); //you need to pass the class type - be aware of it!

要了解有关 json 格式的更多信息,请访问 official json webpage