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

Dar*_*ski 2 java 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()), "");
Run Code Online (Sandbox Code Playgroud)

但是我得到了0个已保存的首选项.我也尝试过HashMap.

m.a*_*icz 7

你不能将数组对象放入首选项中,但是你可以使用字符串来完成它所以你需要的是在从首选项获取值之后保存和反序列化之前序列化.

Libgdx通过提供JSON类来支持序列化.你应该遵循的是:

    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!
Run Code Online (Sandbox Code Playgroud)

要了解有关json格式的更多信息,请访问官方的json网页