Jackson - Deserialize using generic class

gnjago picture gnjago · Jul 26, 2012 · Viewed 177.6k times · Source

I have a json string, which I should deSerialize to the following class

class Data <T> {
    int found;
    Class<T> hits
}

How do I do it? This is the usual way

mapper.readValue(jsonString, Data.class);

But how do I mention what T stands for?

Answer

Eser Ayg&#252;n picture Eser Aygün · Jul 26, 2012

You need to create a TypeReference object for each generic type you use and use that for deserialization. For example -

mapper.readValue(jsonString, new TypeReference<Data<String>>() {});