Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

This code throws ClassCastException:

Java
List<Order> orders = gson.fromJson(json, List.class);
orders.get(0).getId();

Explain and fix it.

Because of type erasure, List.class carries no element type, so Gson does not know the list should hold Order objects and fills it with LinkedTreeMap objects, its generic JSON object representation. The compiler only gives an unchecked warning, so the failure appears later, when orders.get(0) is cast to Order. We fix it by passing the full generic type with a TypeToken: Type t = new TypeToken<List<Order>>(){}.getType(); gson.fromJson(json, t), or TypeToken.getParameterized(List.class, Order.class) when the element class is only known at run time.

Why this question is asked

Reading a JSON array into a list is one of the most common things we do with any JSON library, and this mistake is one of the most common Gson bugs. It is confusing because the line that is wrong does not fail; the exception appears one line later, at a method call that looks perfectly safe. Interviewers ask about it because the explanation requires understanding type erasure and the trick Gson uses to get around it. In this answer, we will reproduce the failure, recap type erasure, see what Gson actually built, apply the TypeToken fix, understand why the anonymous subclass works, and build the type at run time when we need to.

1Reproducing the Problem

Here is the failing code with what happens on each line.

Java
String json = "[{\"id\":7,\"customer\":\"Ana\"},{\"id\":8,\"customer\":\"Bo\"}]";
List<Order> orders = gson.fromJson(json, List.class); // compiles, unchecked warning only
System.out.println(orders.size()); // 2: the list itself is fine
System.out.println(orders.get(0)); // {id=7.0, customer=Ana}
long id = orders.get(0).getId();
// ClassCastException: class com.google.gson.internal.LinkedTreeMap cannot be cast to class Order

Notice the third line. The element prints as a map, and the id is 7.0, a Double. Nothing went wrong while parsing; Gson built exactly what it was asked for. The exception appears only when the compiler-inserted cast to Order runs, at the get(0).getId() call.

2A Quick Recap of Type Erasure

Java generics exist mainly at compile time. The compiler checks that we only put Orders into a List<Order>, and then erases the type argument: at run time, the object is just a List, and the class literal List.class is the same for List<Order>, List<String> and every other list. There is no such thing as List<Order>.class. So when we pass List.class to fromJson, Gson receives a type with no information about the elements at all.

The compiler lets the assignment through with only an unchecked warning, because fromJson(String, Class<T>) returns the raw type List, and assigning a raw List to a List<Order> cannot be checked. Wherever we later take an element out as an Order, the compiler inserts a cast. That cast is where the error surfaces.

3What Gson Built Instead

For an element of unknown type, Gson uses its generic representation of JSON. Each JSON object becomes a LinkedTreeMap<String, Object>, an internal Map implementation that keeps insertion order. Each JSON number becomes a Double by default, because a Double can hold any JSON number Gson might see, which is why the id prints as 7.0. Strings stay strings, and nested arrays become ArrayLists.

What fromJson builds for each target type
Target type passedElements builtorders.get(0).getId()
List.classLinkedTreeMap, numbers as DoubleClassCastException
new TypeToken<List<Order>>(){}.getType()Order objects7
TypeToken.getParameterized(List.class, Order.class)Order objects7

4The Fix: TypeToken

Gson's answer is TypeToken. We create an anonymous subclass of TypeToken with the full generic type as its type argument, and ask it for its Type.

Java
Type listOfOrders = new TypeToken<List<Order>>(){}.getType();
List<Order> orders = gson.fromJson(json, listOfOrders);
System.out.println(orders.get(0).getId()); // 7
System.out.println(orders.get(0).getClass()); // class Order
// Gson 2.10 and later also accept the TypeToken itself and return the right type
List<Order> again = gson.fromJson(json, new TypeToken<List<Order>>(){}); // check your version

Now Gson knows the element type is Order, so it uses the reflective adapter for Order for each element, and the ids are longs again.

5Why the Anonymous Subclass Keeps the Type

If erasure removes type arguments, how does TypeToken know about Order? The trick is the pair of curly braces. new TypeToken<List<Order>>(){} does not create a TypeToken; it declares and instantiates an anonymous subclass of TypeToken<List<Order>>. Erasure removes type arguments from objects and from local variables, but the compiler records the generic signature of a class's superclass in the class file, because it is part of the class declaration.

TypeToken's constructor calls getClass().getGenericSuperclass() on itself, which returns a ParameterizedType describing TypeToken<List<Order>>, and takes its single type argument, List<Order>. That object is a full java.lang.reflect.Type that includes the element type, and that is what we pass to Gson. This general pattern is called a super type token, and other libraries use it too, such as Jackson's TypeReference and Spring's ParameterizedTypeReference.

6Building the Type at Run Time

Sometimes the element class is a variable, for example in a generic helper that receives a Class<T>. We cannot write new TypeToken<List<T>>(){} there, because T is a type variable and not a real class. TypeToken.getParameterized builds the parameterized type from real classes at run time.

Java
static <T> List<T> readList(Gson gson, String json, Class<T> type) {
Type t = TypeToken.getParameterized(List.class, type).getType(); // List<type>
return gson.fromJson(json, t);
}
List<Order> orders = readList(gson, json, Order.class);
System.out.println(orders.get(0).getId()); // 7

The same method builds any shape, for example TypeToken.getParameterized(Map.class, String.class, Order.class) for a Map<String, Order>.

7Follow-up questions

Why does Gson not just throw an error when given List.class?

Because reading a JSON array into a list of untyped values is a legitimate use, for example when the content really is arbitrary. Gson cannot tell whether we wanted that or forgot the element type; the compiler's unchecked warning is the only hint, which is a good reason to treat those warnings seriously.

Would an array type avoid the problem?

Yes. Array types are not erased, so gson.fromJson(json, Order[].class) builds real Order objects, and we can wrap the result with List.of or Arrays.asList. It is a simple alternative when we do not need a specific list type.

Can we stop numbers becoming Double in untyped maps?

Yes, with setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) on the builder, integers become Long and only decimals become Double. It does not fix this bug, because the right fix is to give Gson the real type, but it makes untyped data more faithful.

8Conclusion

In this answer, we saw that List.class is erased and carries no element type, so Gson builds a list of LinkedTreeMap objects with Double numbers, and the ClassCastException appears only at the compiler-inserted cast when we call getId(). A TypeToken created as an anonymous subclass keeps List<Order> in its superclass signature, which Gson reads by reflection, and TypeToken.getParameterized builds the same type at run time when the element class is a variable.

What to say in the interviewAbout 70 seconds aloud

Open with

The problem is type erasure. List.class has no element type, it is the same class object for every kind of list, so Gson has no idea the list should contain Orders.

Then, if they want more

For each JSON object it builds its generic representation, a LinkedTreeMap, with numbers as Double. The assignment to List<Order> compiles with only an unchecked warning, so the list looks fine, and the failure happens at orders.get(0).getId(), where the compiler inserted a cast to Order and the element is really a LinkedTreeMap.

The fix is to give Gson the full generic type with a TypeToken: Type t = new TypeToken<List<Order>>(){}.getType(), then gson.fromJson(json, t). The braces matter: they create an anonymous subclass, and the generic signature of a class's superclass is kept in the class file, so TypeToken reads TypeToken<List<Order>> through getGenericSuperclass and extracts List<Order>.

That is the super type token pattern, which Jackson's TypeReference and Spring's ParameterizedTypeReference also use. If the element class is only known at run time, for example in a generic helper that receives a Class, I use TypeToken.getParameterized(List.class, type).getType() instead.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "This code throws ClassCastException:": https://scrivio-interview-library.netlify.app/java/json-libraries/62f6db3403/