In Gson, how can I deserialize a Map of Lists of arbitrary classes?

181 views Asked by At

I have an API that returns data as follows:

{
    gene: [ ],
    attribute: [ ],
    dataset: [ ]
}

Each List contains an object that should be deserialized to a specific class. For example, each JSON object in the dataset list should be deserialized to a Dataset class. I have not been able to get this to work. Here is my current attempt:

Type listType = new TypeToken<HashMap<String, List<Object>>>() {}.getType();
HashMap<String, List<Object>> map = new Gson().fromJson(json, listType);
List<Dataset> datasets = (List<Dataset>) (Object) map.get("dataset");
Dataset ds = datasets.get(0);

The error I am getting is:

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to Dataset

Thanks in advance.

1

There are 1 answers

0
jds On BEST ANSWER

A colleague suggested writing a wrapper class to describe the schema. This has made serializing and deserializing straightforward.

public class JsonSchema {

    private List<Dataset> datasets;

    ...

    public List<Dataset> getDatasets() {
        return datasets;
    }

    public void setDatasets(List<Dataset> datasets) {
        this.datasets = datasets;
    }

    ...
}

Then, to serialize the JSON, I use the setters and to deserialize the JSON, I write:

JsonSchema jsonSchema = new Gson().fromJson(json, JsonSchema.class);
List<Dataset> datasets = jsonSchema.getDatasets();