Java 将 ArrayList 转换为字符串并返回到 ArrayList? [英] Java convert ArrayList to string and back to ArrayList?
问题描述
我想将一个 ArrayList 保存到 SharedPreferences 所以我需要把它变成一个字符串然后再回来,这就是我正在做的:
I wanted to save an ArrayList to SharedPreferences so I need to turn it into a string and back, this is what I am doing:
// Save to shared preferences
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("myAppsArr", myAppsArr.toString());
editor.commit();
我可以用 String arrayString = sharedPref.getString("yourKey", null);
检索它,但我不知道如何将 arrayString 转换回 ArrayList.怎么办?
I can retrieve it with String arrayString = sharedPref.getString("yourKey", null);
but I don't know how to convert arrayString back into an ArrayList. How can it be done?
我的数组看起来像:
[item1,item2,item3]
推荐答案
您有 2 个选择:
- 手动解析字符串并重新创建数组列表.这会很乏味.
使用 JSON 库(如 Google 的 Gson 库)将对象存储和检索为 JSON 字符串.这是一个轻量级的库,备受推崇和流行.这将是您需要最少工作的理想解决方案.例如,
- Manually parse the string and recreate the arraylist. This would be pretty tedious.
Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,
// How to store JSON string
Gson gson = new Gson();
// This can be any object. Does not have to be an arraylist.
String json = gson.toJson(myAppsArr);
// How to retrieve your Java object back from the string
Gson gson = new Gson();
DataObject obj = gson.fromJson(arrayString, ArrayList.class);
这篇关于Java 将 ArrayList 转换为字符串并返回到 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!