【发布时间】:2015-04-10 11:40:32
【问题描述】:
我希望在 SharedPreferences 中存储一个包含 MyCompositeKeyClass 作为键和 ArrayList 作为值的 HashMap。我该怎么做?
我试过这个:
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"]}}
【问题讨论】:
标签: java android hashmap sharedpreferences gson