🌐
DEV Community
dev.to › emilossola › a-comprehensive-guide-for-java-typereference-249m
A Comprehensive Guide for Java TypeReference - DEV Community
July 10, 2023 - This means that when you use generics, the actual type information is not available at runtime. For example, if you have a List, the type information "String" is not available at runtime due to type erasure.
🌐
Program Creek
programcreek.com › java-api-examples › org.codehaus.jackson.type.TypeReference
org.codehaus.jackson.type.TypeReference Java Examples
* @return */ private static Map<String, ContainerModel> deserializeContainerModelMap( String serializedContainerModel) { Map<String, ContainerModel> containerModelMap = null; ObjectMapper samzaObjectMapper = SamzaObjectMapper.getObjectMapper(); try { if (serializedContainerModel != null) { containerModelMap = samzaObjectMapper.readValue(serializedContainerModel, new TypeReference<Map<String, ContainerModel>>() { }); } } catch (IOException e) { LOG.error("Exception in deserializing container model ", e); } return containerModelMap; }
🌐
Fasterxml
fasterxml.github.io › jackson-core › javadoc › 2.2.0 › com › fasterxml › jackson › core › type › TypeReference.html
TypeReference (Jackson-core 2.2.0 API)
TypeReference ref = new TypeReference<List<Integer>>() { }; which can be passed to methods that accept TypeReference, or resolved using TypeFactory to obtain ResolvedType.
🌐
Java2s
java2s.com › example › java-api › com › fasterxml › jackson › core › type › typereference › typereference-0-25.html
Example usage for com.fasterxml.jackson.core.type TypeReference TypeReference
public List<App> getAllApps() throws Exception { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://" + marathonHost + "/v2/apps"); SimpleRibbonResponse response = utils.simpleRequest(request); Map<String, List<App>> apps = mapper.readValue(response.getContent(), new TypeReference<Map<String, List<App>>>() { });// w w w.j a v a 2 s .
🌐
Northcoder
northcoder.com › post › jackson-object-mapper-which-way-is
Jackson's ObjectMapper and TypeReference | northCoder
January 15, 2021 - This new TypeReference<Map<String, Object>>() {} means the map is no longer untyped. It creates the exact same end result as the first example.
🌐
Java Tips
javatips.net › api › com.fasterxml.jackson.core.type.typereference
Java Examples for com.fasterxml.jackson.core.type.TypeReference
Example 10 · public void testWithBuilder() throws Exception { final ObjectMapper mapper = new ObjectMapper(); final String json = aposToQuotes("{ 'data': [ { 'x': 'x', 'y': 'y' } ] }"); final MyGenericPOJO<MyPOJO> deserialized = mapper.readValue(json, new TypeReference<MyGenericPOJO<MyPOJO>>() { }); assertEquals(1, deserialized.data.size()); Object ob = deserialized.data.get(0); assertNotNull(ob); assertEquals(MyPOJO.class, ob.getClass()); } Example 11 ·
Top answer
1 of 3
267

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);
2 of 3
12

'JavaType' works !! I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution. Code:

JsonMarshallerUnmarshaller<T> {
    T targetClass;

    public ArrayList<T> unmarshal(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        mapper.getDeserializationConfig()
            .withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig()
            .withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
            constructCollectionType(
                ArrayList.class, 
                targetclass.getClass());

        try {
            Class c1 = this.targetclass.getClass();
            Class c2 = this.targetclass1.getClass();
            ArrayList<T> temp = (ArrayList<T>) 
                mapper.readValue(jsonString,  type);
            return temp ;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null ;
    }  
}
Find elsewhere
Top answer
1 of 2
26

In Java generics are more or less gone at runtime. This is called type erasure. So your HashMap<String, Object> will just be HashMap<?, ?> when your programme runs. So Jackson cannot determine the types Stringand Object. That is why you have to create a TypeReference which will preserve that information at runtime so Jackson can deserialise your JSON String into the correct classes.

If you don't specify a type Jackson will still be able to correctly deserialise simple objects like String or numbers but when a more complex object is encountered it will simply deserialise them into LinkedHashMap which will then most likely lead to a ClassCastException when you try to access the deserialised object.

2 of 2
9

This TypeReference<T> implements Comparable<TypeReference<T>> is part of jackon library. And this is part of com.fasterxml.jackson.core.type. From the API documentation:

This generic abstract class is used for obtaining full generics type information by sub-classing; it must be converted to ResolvedType implementation (implemented by JavaType from "databind" bundle) to be used. Class is based on ideas from http://gafter.blogspot.com/2006/12/super-type-tokens.html, Additional idea (from a suggestion made in comments of the article) is to require bogus implementation of Comparable (any such generic interface would do, as long as it forces a method with generic type to be implemented). to ensure that a Type argument is indeed given. Usage is by sub-classing: here is one way to instantiate reference to generic type List:

TypeReference ref = new TypeReference<List>() { }; which can be passed to methods that accept TypeReference, or resolved using TypeFactory to obtain ResolvedType.

This is basically used to de-serialize the Generic type of JSON objects, for example the JAVA Collection objects as below:

public List<Double> getDoubleList() {

  return getObjectFromJson(new TypeReference<List<Double>>() {
  });
}


public <T> T getObjectFromJson(String jsonString, final TypeReference<T> typeReference) {
  try {
    return new ObjectMapper().readValue(jsonString, typeReference);
  } catch (JsonProcessingException e) {
    // TODO
  }
}
🌐
Spring
docs.spring.io › spring-framework › docs › current › javadoc-api › org › springframework › asm › TypeReference.html
TypeReference (Spring Framework 7.0.8 API)
public class TypeReference extends ... where the referenced type is appearing (for example, an 'extends', 'implements' or 'throws' clause, a 'new' instruction, a 'catch' clause, a type cast, a local variable declaration, etc)....
🌐
Adobe Developer
developer.adobe.com › experience-manager › reference-materials › 6-5 › javadoc › com › fasterxml › jackson › core › type › TypeReference.html
TypeReference (The Adobe AEM Quickstart and Web Application.)
TypeReference ref = new TypeReference<List<Integer>>() { }; which can be passed to methods that accept TypeReference, or resolved using TypeFactory to obtain ResolvedType.
🌐
Medium
medium.com › @poojaauma › enhancing-deserialization-safety-in-java-with-typereference-ea110ece6994
Enhancing Deserialization Safety in Java with TypeReference | by Umadevi R | Medium
November 7, 2024 - When working with JSON in Java, you’ve probably come across situations where deserializing JSON into complex or generic types like List<User> or Map<String, Object> can be challenging. Java’s type erasure makes it hard for libraries like Jackson to determine the exact type of collection elements, which can lead to runtime errors or even vulnerabilities. Fortunately, Jackson’s TypeReference offers a solution to these problems.
🌐
Quora
quora.com › What-is-TypeReference-in-Java
What is TypeReference in Java? - Quora
Answer (1 of 2): I don’t think that java by default comes with any TypeReference class or interface. Although Jackson, which is a pretty popular Json parsing library, has TypeReference abstract class. It is used with object mapper to give a reference of what type of data you want after the ...
🌐
Baeldung
baeldung.com › home › json › jackson › map serialization and deserialization with jackson
Map Serialization and Deserialization with Jackson | Baeldung
January 8, 2024 - String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}"; TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {}; Map<MyPair,MyPair> map = mapper.readValue(jsonInput, typeRef);
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Spring ParameterizedTypeReference Example - Java Code Geeks
August 11, 2025 - In this example, the getAllProducts() method sends a GET request to /products, using an anonymous subclass of ParameterizedTypeReference<List<Product>> to capture the generic type at runtime.
🌐
Baeldung
baeldung.com › home › json › jackson › deserialize generic type with jackson
Deserialize Generic Type with Jackson | Baeldung
September 17, 2025 - As well known, Java erases generic type information during compilation, but we can take advantage of the power of anonymous inner classes to preserve the type information during compile time. Jackson provides the abstract class TypeReference to obtain the type information from the derivated ...
🌐
Fasterxml
fasterxml.github.io › jackson-core › javadoc › 1.9 › org › codehaus › jackson › type › class-use › TypeReference.html
Uses of Class org.codehaus.jackson.type.TypeReference (Jackson JSON Processor)
JavaScript is disabled on your browser · Overview · Package · Class · Deprecated · Index · Frames · No Frames · All Classes · Uses of Class org.codehaus.jackson.type.TypeReference
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 3129
TypeReference not working as expected in generic context · Issue #3129 · FasterXML/jackson-databind
April 22, 2021 - public class Main { private static final ObjectMapper objectMapper = new ObjectMapper(); public static void main(String[] args) throws JsonProcessingException { String json = "{\"name\": \"Steve\"}"; Person p = getResult(json); } private static <T> T getResult(String json) throws JsonProcessingException { return objectMapper.readValue(json, new TypeReference<T>() {}); } private static class Person { public String name; } }