How to Fix ClassCastException with Gson When Deserializing JSON to Custom Objects

Question

Why am I receiving a ClassCastException when trying to deserialize JSON to my custom Product class with Gson?

String name = Util.stringToArray(message).get(i).getName();

Answer

When deserializing JSON strings into Java objects using Gson, you may encounter a ClassCastException, specifically when Gson interprets the data as LinkedTreeMap instead of your custom class. This occurs when Gson cannot determine the target type correctly during deserialization.

public static ArrayList<Product> stringToArray(String s) {
    Gson g = new Gson();
    Type listType = new TypeToken<ArrayList<Product>>(){}.getType();
    ArrayList<Product> list = g.fromJson(s, listType);
    return list;
}

Causes

  • Gson does not know the type of elements in the ArrayList when converting from JSON to Java objects, leading it to use a default type (LinkedTreeMap).
  • The TypeToken is not utilized correctly or not respected during the deserialization process.

Solutions

  • Use a concrete TypeToken to inform Gson about the specific type being deserialized.
  • Change the type parameter in your stringToArray method to ensure type information is preserved during deserialization.

Common Mistakes

Mistake: Not specifying the correct type token when deserializing.

Solution: Ensure that the TypeToken accurately reflects the generic type you expect, such as ArrayList<Product>.

Mistake: Using raw types instead of proper generic declarations.

Solution: Always specify types with generic collections to prevent type erasure issues.

Helpers

  • Gson deserialization
  • ClassCastException
  • LinkedTreeMap
  • Gson TypeToken
  • Java JSON parsing
  • custom objects Gson
  • Product class Gson

Related Questions

⦿Why is the Letter 'f' Used After Float Values in Java?

Explore the reason behind using f after float values in Java and learn its importance in defining floatingpoint literals.

⦿How to List Files in a Directory Matching a Pattern in Java?

Learn how to list files in a directory that match a specific pattern using Java including regex support and typesafe collections.

⦿How to Check if a Boolean is Null in Java?

Learn how to properly check for null values in Boolean variables in Java with examples and common mistakes.

⦿How to Safely Check if an Object is Null in Java?

Learn how to safely check for null objects in Java avoiding exceptions while retrieving local images.

⦿How to Resolve the 'Could Not Create the Java Virtual Machine' Error in Apache Tomcat?

Learn how to fix the Could not create the Java Virtual Machine error when launching Tomcat in the Java Wicket framework. Stepbystep guide included.

⦿How to Convert Minutes into Hours and Minutes Format (hh:mm) in Java?

Learn to convert minutes to hours and minutes hhmm format in Java with clear code examples and stepbystep explanations.

⦿How to Configure a Spring REST Service to Exclude Null Values from JSON Responses

Learn how to configure a Spring REST service to automatically exclude null values from JSON responses using Jackson ObjectMapper.

⦿Understanding Thread States in VisualVM: Sleeping, Waiting, Parking, and Monitor

Explore the differences between Sleeping Waiting Parked and Monitor thread states in VisualVM and understand what suspends a threads execution.

⦿How to Remove Non-Printable Unicode Characters in Java

Learn how to effectively replace nonprintable Unicode characters in Java strings with expert insights and code examples.

⦿Why is the long Data Type Not Supported in Java's Switch Statement?

Discover why Javas switch statement does not support the long data type and explore alternatives.

© Copyright 2025 - CodingTechRoom.com

close