Java的ArrayList的转换为字符串,返回ArrayList的? [英] Java convert ArrayList to string and back to ArrayList?
问题描述
我想保存一个ArrayList共享preferences所以我需要把它变成一个字符串回来了,这是我在做什么:
//保存到共享preferences
共享preferences共享preF = this.get preferences(Activity.MODE_PRIVATE);
共享preferences.Editor编辑= this.get preferences(Activity.MODE_PRIVATE).edit();
editor.putString(myAppsArr,myAppsArr.toString());
editor.commit();
我可以用检索字符串arrayString =共享pref.getString(yourKey,NULL);
,但我不知道如何转换arrayString回到一个ArrayList。如何能做到?
我的阵列看起来像:
[项目1,项目2,项目3]
您有两个选择:
- 手动解析字符串并重新创建ArrayList中。这将是pretty乏味。
-
使用一个JSON库像谷歌的 GSON 库存储和检索对象作为JSON字符串。这是一个轻量级的库,以及重视和欢迎。这将是你的情况需要最小的工作的理想解决方案。如,
//如何储存JSON字符串
GSON GSON =新GSON();
//这可以是任何对象。不必成为一个ArrayList。
JSON字符串= gson.toJson(myAppsArr);//如何找回您的Java对象从字符串返回
GSON GSON =新GSON();
数据对象的obj = gson.fromJson(arrayString,ArrayList.class);
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();
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?
My array looks something like:
[item1,item2,item3]
You have 2 choices :
- 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屋!