我明白了:
LinkedHashSet<Object> list = new LinkedHashSet<>();
list.add(new MyObject1());
list.add(new MyObject2());
list.add(new JSONObject());
list.add(new ObjectICannotEdit());
我保存到SharedPreferences列表:
SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE).edit();
final Gson gson = new Gson();
editor.putString(KEY, gson.toJson(list));
editor.commit();
我这样加载:
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, context.MODE_PRIVATE);
String json = prefs.getString(KEY, null);
Gson gson = new Gson();
Type type = new TypeToken<LinkedHashSet<Object>>(){}.getType();
LinkedHashSet<Object> result = gson.fromJson(json, type);
for (Object t : result) {
if(t instanceof MyObject1){
//cant get here because t is a instance of LinkedTreeMap
}
}
你能告诉我在保存和加载时如何保持列表中每个对象的类型吗?
答案 0 :(得分:0)
我建议您使用Serialization
保存数据集。
在官方文档中了解详情:https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html(或稍微谷歌)
确保自定义类中的implement Serializable
!
e.g。
public class MyObject1 implements Serializable {
...
}