Question

I have an ArrayList of objects(tweet is a class that I have defined in my package). Now, I have written this ArraList as a JSON object into a file using GSON. Moving on, I am now reading this JSON object into an ArrayList using GSON. However, when I iterate through this newly read ArrayList, I am not able to cast it back into a tweet object. Even though the ArrayList is actually a collection of tweet objects in itself. The exception I am getting is : com.google.gson.internal.LinkedTreeMap cannot be cast to tweet

contents_array_tweets is an arraylist of tweet objects.

contents_array has also been declared as an arraylist of tweet objects.

Here is the code:

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.
    }
Was it helpful?

Solution

ob.contents_array = gson.fromJson(ob.file_contents, ArrayList.class);

Instead of a raw ArrayList.class you should use a TypeToken to tell Gson the actual runtime type of the ArrayList's type parameter:

ob.contents_array = gson.fromJson(ob.file_contents,
    new TypeToken<ArrayList<tweet>>(){}.getType());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top