【问题标题】:GSON Deserialization to an ArrayList<T> not workingGSON 反序列化为 ArrayList<T> 不起作用
【发布时间】:2014-04-24 08:11:46
【问题描述】:

我有一个对象的 ArrayList(tweet 是我在我的包中定义的一个类)。现在,我已使用 GSON 将此 ArraList 作为 JSON 对象写入文件。继续前进,我现在正在使用 GSON 将这个 JSON 对象读入一个 ArrayList。但是,当我遍历这个新读取的 ArrayList 时,我无法将其转换回推文对象。尽管 ArrayList 实际上本身就是推文对象的集合。我得到的例外是: com.google.gson.internal.LinkedTreeMap 无法转换为推文

contents_array_tweets 是推文对象的数组列表。

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

【问题讨论】:

  • 请删除所有代码,这是不需要来理解问题;显示代码的小非工作部分。

标签: java json deserialization gson json-deserialization


【解决方案1】:
ob.contents_array = gson.fromJson(ob.file_contents, ArrayList.class);

您应该使用TypeToken 来告诉 Gson ArrayList 的类型参数的实际运行时类型,而不是原始的 ArrayList.class

ob.contents_array = gson.fromJson(ob.file_contents,
    new TypeToken<ArrayList<tweet>>(){}.getType());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 2012-06-14
    • 2019-01-17
    相关资源
    最近更新 更多