我有一个对象的ArrayList(tweet是我在包中定义的类)。现在,我已使用 GSON 将这个 ArraList 作为 JSON 对象写入文件中。接下来,我现在使用 GSON 将此 JSON 对象读入 ArrayList。但是,当我迭代这个新读取的 ArrayList 时,我无法将其转换回 tweet 对象。尽管 ArrayList 实际上本身就是 tweet 对象的集合。我得到的异常(exception)是: com.google.gson.internal.LinkedTreeMap 无法转换为 tweet
contents_array_tweets 是 tweet 对象的数组列表。
contents_array 也被声明为 tweet 对象的数组列表。
这是代码:
f.write_file("Content_Array_JSON_full.json", gson.toJson(ob.contents_array_tweets), false);
ob.read_file("Content_Array_JSON_full.json",f);
ob.contents_array = gson.fromJson(ob.file_contents, ArrayList.class);
for(i=0; i<ob.contents_array.size(); i++){
stn_1 = ob.contents_array.get(i).stemmed_nouns;
ob.contents_array.get(i).sim_tw = new HashMap<Integer, Double>();
//This is where I get the exception. I am not able to access stemmed_nouns and sim_tw which are class variables of tweet.
}
最佳答案
ob.contents_array = gson.fromJson(ob.file_contents, ArrayList.class);
您应该使用 TypeToken
而不是原始的 ArrayList.class
告诉 Gson ArrayList 类型参数的实际运行时类型:
ob.contents_array = gson.fromJson(ob.file_contents,
new TypeToken<ArrayList<tweet>>(){}.getType());
关于java - GSON 反序列化为 ArrayList<T> 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23263353/