Reputation: 1982
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to anindya.fb.datamodel.Datum
I have a HashMap
:
static HashMap<String, Datum> favoriteList = new HashMap<>();
and I write it to GSON in the following way:
String json = gson.toJson(favoriteList);
mEditor.putString(PREF_FAVORITE, json);
mEditor.commit();
and get it like this:
gson = new Gson();
String json = mPref.getString(PREF_FAVORITE, "");
if (json.equals(""))
favoriteList = new HashMap<>();
else
favoriteList = gson.fromJson(json, HashMap.class);
To send back a part of this HashMap
based on a value, I am doing this:
ArrayList<Datum> data = new ArrayList<>();
for(String key: favoriteType.keySet()) {
if(favoriteType.get(key).equals(type)) { //type is a parameter to this method
data.add(favoriteList.get(key));
}
}
return data;
However when I try to access this data, I get this error:
final Datum curData = data.get(position);
gives an error:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to anindya.fb.datamodel.Datum
I came across some posts which mention adding lines in the proguard
file.
-keepattributes *Annotation*
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }
but that did not fix the error. Any help would be appreciated.
Upvotes: 0
Views: 1116
Reputation: 3863
You need to get the type of
HashMap<String, Datum>
so do this,Type type = new TypeToken<HashMap<String, Datum>>(){}.getType();
then
favoriteList = gson.fromJson(json, type);
Upvotes: 1
Reputation: 492
Try something like this...
public Map<String, Datum> toMap(String jsonString) {
Type type = new TypeToken<Map<String, Datum>>(){}.getType();
Gson gson = new GsonBuilder().create();
Map<String, Datum> map = gson.fromJson(jsonString, type);
return map;
}
Upvotes: 0
Reputation: 1036
The issue is you're storing a hashmap with type information that's getting dropped when you're reading it.
Change
favoriteList = gson.fromJson(json, HashMap.class);
to
favoriteList = gson.fromJson(json, new TypeToken<HashMap<String, Datum>>(){}.getType);
Upvotes: 3