Android JSON parsing on collision with GSON: LinkedTreeMap cannot be cast to object
I am trying to store a list of objects in SharedPreferences, so I am using Gson to convert a list of objects to JSON and back. However, when I save, then retrieve the list of objects, and the ListView adapter is applied to the new list, I get the following error:
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)
where the error points to this line in the list:
Folder folder = folderList.get(position);
When storing a list of objects, I use the following:
//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);
where the last line just stores the line in SharedPreferences. When you fetch the list from SharedPreferences I use the following:
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<>();
}
If that helps, here's how my Folder class is defined:
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<>();
}
}
source to share
Not an answer to your question, but a suggestion. I have also been trying to work with json in Android recently and have researched a lot which one to use jackson or gson. It looks like there are two benefits to Jackson:
- Jackson's performance is better than gson.
- If you use the same on the server side you get consistency.
Ref: [Be-lazy-productive-android] [1] http://java.dzone.com/articles/be-lazy-productive-android
source to share