Explain Codes LogoExplain Codes Logo

Deserialize a List object with Gson?

java
type-erasure
gson
deserialization
Nikita BarsukovbyNikita Barsukov·Aug 31, 2024
TLDR

To deserialize a List<T> using Gson, utilize a TypeToken to preserve the generic type information:

Type targetType = new TypeToken<List<YourType>>(){}.getType(); List<YourType> deserializedList = new Gson().fromJson(jsonString, targetType);

Swap out YourType with the class type of your list elements and replace jsonString with your JSON data. It's like swapping tires, fast and efficient.

Subdue type erasure with anonymous subclass

In Java, type erasure in generics is like an unexpected villain. It removes (erases) generic type information during compilation. Here's the batman utility belt for you:

  1. With collections like List<T>, be sure to create an anonymous subclass of TypeToken. It's like having an extra layer of protective armor against type erasure.
  2. Have an array of objects? Deserializing them directly might seem tempting, like a forbidden fruit, but don't bite. Convert the array to a List<T> to make the most of Gson's prowess:
    YourType[] array = new Gson().fromJson(jsonString, YourType[].class); List<YourType> list = new ArrayList<>(Arrays.asList(array));
  3. Shun using a plain List.class when deserializing. It pokes holes in your type info, making potential ClassCastException your unwanted guest.

Tackle complex scenarios with Parameterized Type

Some JSON arrays can be more twisted than pretzels with deep nesting or inconsistent types. The following solutions are like Houdini's tricks to unravel them:

  1. Parameterized Type: Bring in ParameterizedType like a GPS for a complex road trip. It creates precise generic type representation helping Gson navigate accurately through nested objects.
  2. Custom Classes: Forge your own wrapping class, ListOfJson<T>, to give Gson a pair of X-Ray glasses, letting it detect the exact List type you're deserializing.
  3. Error Handling: Don't forget to have an umbrella (try-catch blocks) for potential rain (malformed JSON data). It saves from the sudden shower of JsonParseException.

Master common pitfalls and solutions

Guardian angel null-check

Before going on a deserialization spree, always ensure the JSON string is not null. A simple null-check is your guardian angel that keeps away the evil NullPointerException.

Role-play to modifiable list

Post-deserialization, if you want your list to be ready for any role-play (add, remove elements), don't forget to call for a suit change:

List<YourType> modifiableList = new ArrayList<>(Arrays.asList(deserializedArray));

A dashing new suit for the elements to dance around (edit).

Deep dive into parameterized lists

For the love of diving, deserializing lists with parameterized types invites you for a deep sea adventure. TypeToken.getParameterized() is your oxygen mask, keep it handy while dealing with types like List<Map<String, String>>:

Type targetType = TypeToken.getParameterized(List.class, Map.class, String.class, String.class).getType(); List<Map<String, String>> deserializedList = new Gson().fromJson(jsonString, targetType);

Custom list deserialization

For diverse JSON arrays, gift yourself a getList method like the universal TV remote control. It simplifies deserialization across several types:

public <T> List<T> getList(Type listType, String jsonArray) { return new Gson().fromJson(jsonArray, listType); }

TV channels or JSON types, change as you wish!