如何存储<hashmap <mycompositekeyclass,arraylist <myclass =“”>&gt;在SharedPreferences?</hashmap <mycompositekeyclass,>

时间:2015-04-10 11:40:32

标签: java android hashmap sharedpreferences gson

我希望存储一个HashMap,它包含MyCompositeKeyClass作为键,ArrayList作为SharedPreferences内的值。我怎么能这样做?

我试过了:

 public void saveLessonMap(Context context, HashMap<dayKey, ArrayList<Lesson>> lessonMap){
   MapWrapper wrapper = new MapWrapper(lessonMap);
   String serializedMap = gson.toJson(wrapper);

    appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context);

    SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();

    prefsEditor.putString(KEY, serializedMap);
    prefsEditor.commit();


}

 public HashMap<dayKey, ArrayList<Lesson>> getLessonMap(Context context){
    appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    String wrapperStr = appSharedPrefs.getString(KEY, "");
    MapWrapper wrapper = gson.fromJson(wrapperStr, MapWrapper.class);
    return wrapper.getMap();
}

但得到了:

fromJson com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 10

JSON:{"map":{"com.example.ruslanposhuk.timetable.model.dayKey@ca81be1c":[{"bTime":{"year":2015,"month":4,"dayOfMonth":7,"hourOfDay":8,"minute":30,"second":0},"eTime":{"year":2015,"month":4,"dayOfMonth":7,"hourOfDay":9,"minute":50,"second":0},"name":"Wednesday1","room":"114","teacherName":"John Smith"},{"bTime":{"year":2015,"month":4,"dayOfMonth":7,"hourOfDay":10,"minute":0,"second":0},"eTime":{"year":2015,"month":4,"dayOfMonth":7,"hourOfDay":11,"minute":20,"second":0},"name":"Wednesday2","room":"254","teacherName":"Bob Moore"},{"bTime":{"year":2015,"month":4,"dayOfMonth":7,"hourOfDay":12,"minute":0,"second":0},"eTime":{"year":2015,"month":4,"dayOfMonth":7,"hourOfDay":13,"minute":20,"second":0},"name":"Wednesday3","room":"178","teacherName":"Peter Johnson"}],"com.example.ruslanposhuk.timetable.model.dayKey@28f78912":[{"bTime":{"year":2015,"month":4,"dayOfMonth":7,"hourOfDay":8,"minute":30,"second":0},"eTime":{"year":2015,"month":4,"dayOfMonth":7,"hourOfDay":9,"minute":50,"second":0},"name":"Tuesday1","room":"114","teacherName":"John Smith"},{"bTime":{"year":2015,"month":4,"dayOfMonth":7,"hourOfDay":10,"minute":0,"second":0},"eTime"]}}

2 个答案:

答案 0 :(得分:0)

ArryList<MyClass>转换为json数据并存储它。使用gson库将ArrayList转换为JSON String格式。

答案 1 :(得分:0)

  Gson gson  =
        new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting().create();
java.lang.reflect.Type type = new TypeToken <HashMap<dayKey, ArrayList<Lesson>>>(){}.getType();

保存:String json = gson.toJson(lessonMap, type);

正在加载:HashMap<dayKey, ArrayList<Lesson>> lessonMap = gson.fromJson(json, type);