我想将HashMap
保存到SharedPreference
文件。为此,我通过对象使用Gson
到serialise-deserialise
从HashMap
创建String
对象时出现此错误。
Expected a string but was BEGIN_OBJECT at line 1 column 4
这就是我尝试使用Gson
的方式。
public class Point {
public int action;
....
}
....
public ArrayList<Point> gestInstance;
public HashMap<String, ArrayList<Point>> savedGest;
....
// Storing as a String in SharedPreference
String serialisedGestures = gson.toJson(savedGest);
mSharedPref.edit()
.putString("saved_gestures", serialisedGestures)
.commit();
// Retrieving from SharedPreference
String serialisedGest = mSharedPref.getString("saved_gest",
"not_assigned");
Gson gson = new Gson();
Type gestType = new TypeToken<HashMap<String, ArrayList<Point>>>() {
}.getType();
savedGest = gson.fromJson(serialisedGest, gestType); // Error!!
为什么会出错?有人可以建议替代或解决方法吗?
答案 0 :(得分:4)
我们可以使用GSON
lib
保存到SharedPreferences
HashMap<String,String> mHashmap = new HashMap<>();
mHashmap.put("test","SO");
Gson gson = new Gson();
String strInput = gson.toJson(mHashmap);// save this string in sharedPreferences
从SharedPreferences中检索HashMap
String strOutput = "";//Retrive text from sharedPreferences
Type type = new TypeToken<HashMap<String, String>>(){}.getType();
HashMap<String, String> map = gson.fromJson(strOutput, type);