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
}