Jackson - Deserialize Generic class variable

generics, jackson, java, json

Solution

You will need to build `JavaType` explicitly, if generic type is only dynamically available:

// do NOT create new ObjectMapper per each request!
final ObjectMapper mapper = new ObjectMapper();

public Json<T> void deSerialize(Class<T> clazz, InputStream json) {
    return mapper.readValue(json,
      mapper.getTypeFactory().constructParametricType(Json.class, clazz));
}

Problem

I had posted the question wrongly. I am posting the question correctly here ... I am getting a json string as a HTTP response. I know the structure of it. It is as follows: ``` public class Json<T> { public Hits<T> hits; } public class Hits<T> { public int found; public int start; public ArrayList<Hit<T>> hit; } public class Hit<T> { public String id; public Class<T> data; } ``` The "data" field can belong to any class. I will know it at runtime only. I will get it as a parameter. This is how I am deserializing. ``` public <T> void deSerialize(Class<T> clazz) { ObjectMapper mapper = new ObjectMapper(); mapper.readValue(jsonString, new TypeReference<Json<T>>() {}); } ``` But I am getting an error - cannot access private java.lang.class.Class() from java.lang.class. Failed to set access. Cannot make a java.lang.Class constructor accessible

Original source

Related problems