Jackson - Deserialize Generic class variable

Viewed 36355

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

6 Answers

For me something like this works for similar case

public <T> T jsonToObject(String jsonContainsObject, Class<T> objectType) {
       ObjectMapper objectMapper = new ObjectMapper();
       try {
         return objectMapper.readValue(jsonContainsObject, objectType);
       } catch (JsonProcessingException e) {
         //Your exception handling
       }
    return null; 
}
Related