简体   繁体   中英

Gson type cast error

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.

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);

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);

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM