How to use Jackson's TypeReference with generics?
TypeReference
requires you to specify parameters statically, not dynamically, so it does not work if you need to further parameterize types.
What I think you need is JavaType
: you can build instances dynamically by using TypeFactory
. You get an instance of TypeFactory
via ObjectMapper.getTypeFactory()
. You can also construct JavaType
instances from simple Class
as well as TypeReference
.
One approach will be to define a Jackson JavaType representing a list of items of type clazz. You still need to have access to the class of the generic parameter at runtime. The usual approach is something like
<T> class XX { XX(Class<T> clazz, ...) ... }
to pass the class of the generic parameter into the generic class at construction.
Upon access to the Class clazz variable you can construct a Jackson JavaType representing, for example, a list of items of class clazz with the following statement.
JavaType itemType = mapper.getTypeFactory().constructCollectionType(List.class, clazz);
I hope it helped. I am using this approach in my own code.
Try this:
import com.fasterxml.jackson.databind.ObjectMapper; import java.lang.reflect.Array; import java.util.Arrays; ... public static <TargetType> List<TargetType> convertToList(String jsonString, Class<TargetType> targetTypeClass) { List<TargetType> listOfTargetObjects = null; ObjectMapper objectMapper = new ObjectMapper(); TargetType[] arrayOfTargetType = (TargetType[]) Array.newInstance(targetTypeClass, 0); try { listOfTargetObjects = (List<TargetType>) Arrays.asList(objectMapper.readValue(jsonString, arrayOfTargetType.getClass())); } catch (JsonMappingException jsonMappingException) { listOfTargetObjects = null; } catch (JsonProcessingException jsonProcessingException) { listOfTargetObjects = null; } catch (Exception exception) { listOfTargetObjects = null; } return listOfTargetObjects; }...