Gson: Cast Gson LinkedTreeMap to a generic ArrayList of different types

Viewed 992

I know similar questions have been asked here before but the solutions here, here and here really aren't helpful for me because they deal with a generic List that contains list of a single type.

I've got a POJO like the following that I parse into JSON using Gson.toJson(), save in my database table as a string and get it back using Gson.fromJson().

public class MyClass implements Serializable{
    private HashMap<String, List> statistic;

    @SuppressWarnings("rawtypes")
    public void setStatistic(HashMap<String, List> statistic) {
        this.statistic = statistic;
    }

    @SuppressWarnings("rawtypes")
    public HashMap<String, List> getStatistic() {
        return statistic;
    }
}

Here is the problem. The generic List in the HashMap contains the following information.

List<ClassOne> one = new ArrayList<ClassOne>();
List<ClassTwo> two = new ArrayList<ClassTwo>();

HashMap<String, List> list = new HashMap<String, List>();
list.put("one", one);
list.put("two", two);

Now when I parse the JSON back to MyClass I get back the HashMap with the generic list. But the information about ClassOne and ClassTwo are lost and I just get the information in them as LinkedTreeMap which can't be cast to the mentioned types again by

MyClass myObject = gson.fromJson(jsonString, MyClass.class);

HashMap<String, List> statistic = myObject.getStatistic();

List<ClassOne> one = (List<ClassOne>) statistic.get("one");
List<ClassTwo> one = (List<ClassTwo>) statistic.get("two");

How do I solve this problem? I can't change the structure of my POJO to have two ArrayLists instead of one HashMap so I'm stuck with this.

0 Answers
Related