1

I use Jackson to deserialize a generic type like this:

ListResponse<Product> = objectMapper.readValue(json, new TypeReference<ListResponse<Product>>() {});  
ListResponse<User> = objectMapper.readValue(json, new TypeReference<ListResponse<User>>() {});    

and so on for every generic type the ListResponse will include.
This works OK, but I would like to create a method that will take as argument a generic type, and return a ListResponse of that generic type.

Something like this:

public static <T> T fromJsonWithListResponse(String json) {    
    return objectMapper.readValue(json, new TypeReference<ListResponse<T>>(){});
}

or this:

public static <T> T fromJsonWithListResponse(final Class<T> clazz, String json) {    
    return objectMapper.readValue(json, new TypeReference<clazz>(){}); // compile error
}

but it converts the result to a LinkedHashMap.

ListResponse is a wrapper class around List:

public class ListResponse<T> extends Response {
    private List<T> items;
    // other fields
    // getters and setters
}
Andy Res
  • 15,963
  • 5
  • 60
  • 96
  • Look at this answer: https://stackoverflow.com/questions/6846244/jackson-and-generic-type-reference?rq=1 That should work for your case as well. – Martina Jun 24 '14 at 12:46

0 Answers0