简体   繁体   English

Gson类型转换错误

[英]Gson type cast error

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to anindya.fb.datamodel.Datum

I have a HashMap : 我有一个HashMap

static HashMap<String, Datum> favoriteList = new HashMap<>();

and I write it to GSON in the following way: 然后通过以下方式将其写入GSON:

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: 要基于值发回此HashMap的一部分,我正在这样做:

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. 我遇到了一些帖子,提到在proguard文件中添加行。

-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(); 您需要获取HashMap<String, Datum>的类型,执行此操作, 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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