From Jackson 2.5, an elegant way to solve that is using the
TypeFactory.constructParametricType(Class parametrized, Class... parameterClasses) method that allows to define straigthly a Jackson JavaType
by specifying the parameterized class and its parameterized types.
Supposing you want to deserialize to Data<String>
, you can do :
// the json variable may be a String, an InputStream and so for...
JavaType type = mapper.getTypeFactory().constructParametricType(Data.class, String.class);
Data<String> data = mapper.readValue(json, type);
Note that if the class declared multiple parameterized types, it would not be really harder :
class Data <T, U> {
int found;
Class<T> hits;
List<U> list;
}
We could do :
JavaType type = mapper.getTypeFactory().constructParametricType(Data.class, String.class, Integer);
Data<String, Integer> data = mapper.readValue(json, type);