使用Gson存储HashMap时出现问题

时间:2014-09-17 15:16:57

标签: android gson

我想将HashMap保存到SharedPreference文件。为此,我通过对象使用Gsonserialise-deserialiseHashMap创建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!!

为什么会出错?有人可以建议替代或解决方法吗?

1 个答案:

答案 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);