Based on this question How to get a class instance of generics type T I have implemented the following class:
public class OkJsonConverter<T> {
final Class<T> typeParameterClass;
public OkJsonConverter(Class<T> typeParameterClass) {
this.typeParameterClass = typeParameterClass;
}
protected T processJson(String json) throws OkClientException {
T object = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode jsonNode = objectMapper.readTree(json);
if (jsonNode.get("error_code") != null) {
Error error = objectMapper.treeToValue(jsonNode, Error.class);
throw new OkClientException("API returned error", error);
} else {
object = objectMapper.treeToValue(jsonNode, typeParameterClass);
}
} catch (IOException e) {
throw new OkClientException("unable to process json", e);
}
return object;
}
}
I can use this class with a generic parameters, for example:
return new OkJsonConverter<User>(User.class).processJson(response.getBody());
but right now I'm struggling how to make it working with a nested generic parameter like this one List<Method>
This code doesn't work:
return new OkJsonConverter<List<Method>>(List<Method>.class).processJson(response.getBody());
Please help to change this code in order to get it working.