我正在尝试将对象列表存储到SharedPreferences中,因此我使用Gson将对象列表转换为JSON并再次返回。但是,当我存储然后检索对象列表并且ListView的适配器应用于新列表时,我收到以下错误:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to appuccino.simplyscan.Objects.Folder
at appuccino.simplyscan.Extra.DocumentAdapter.getView(DocumentAdapter.java:117)
其中错误指向列表适配器中此行:
Folder folder = folderList.get(position);
存储对象列表时,我使用以下内容:
//folderList is a List<Folder> folderList = new ArrayList<>();
folderList.add(0, newFolder);
Gson gson = new Gson();
String newFoldersJson = gson.toJson(folderList);
PrefManager.putString(PrefManager.FOLDER_JSON, newFoldersJson);
其中最后一行只是将字符串存储到SharedPreferences中。从SharedPreferences检索列表时,我使用以下内容:
public static List<Folder> loadFolders(MainActivity main){
//JSON containing a list of folder objects
String foldersJSON = PrefManager.getString(PrefManager.FOLDER_JSON, "");
if(!foldersJSON.isEmpty()){
Gson gson = new Gson();
List<Folder> folderList = gson.fromJson(foldersJSON, List.class);
return folderList;
}
return new ArrayList<>();
}
如果有帮助,这就是我的Folder类的定义方式:
public class Folder {
private String name;
private List<String> docNameList;
private transient List<Document> docList;
public Folder(String n) {
name = n;
docList = new ArrayList<>();
docNameList = new ArrayList<>();
}
}
答案 0 :(得分:-3)
不是你问题的答案,而是一个建议。我最近也尝试在Android中使用json,并研究了很多关于使用jackson或gson的方法。好像杰克逊有两个优点:
价: [待懒惰生产-机器人] [1] http://java.dzone.com/articles/be-lazy-productive-android