Gson是一個Java庫,用於將Java對象轉換成JSON字符串和副詩句。 我在我的項目中遇到過同樣的問題,並使用Gson將HashMap轉換爲字符串,將其保存到SharedPreferences中,然後將其恢復到其他活動中。
要存儲的地圖:
SharedPreferences preferences = getSharedPreferences("com.your.package", MODE_PRIVATE);
Type genericType = new TypeToken<HashMap<String, String>>() {}.getType();
String serializedHashMap = Helpers.serializeWithJSON(your_hashmap, genericType);
preferences.edit().putString("Somename", serializedHashMap).commit();
serializeWithJSON():
public static String serializeWithJSON(Object o, Type genericType) {
Gson gson = new Gson();
return gson.toJson(o, genericType);
}
反序列化:
Gson gson = new Gson();
Type genericType = new TypeToken<HashMap<String, String>>() {}.getType();
HashMap<String, String> hashMap = gson.fromJson(preferences.getString("Somename", "Errormessage"), genericType);
持久地將其存儲在一個文件中,使用amalBit的答案。
http://stackoverflow.com/questions/9227016/how-to-store-hashmap-on-android –
如果它是一個很大的散列圖,也許你想存儲在一個分區 – lelloman