Type Token

import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

Problem That TypeToken solves

// Consider these two lists
List<String> stringList = new ArrayList<>();
List<Integer> integerList = new ArrayList<>();

// At runtime, due to type erasure, Java sees both as just List
// This means we can't directly tell Gson what type to deserialize to

// with the help of TypeToken we tell Gson about type of data in process of ser and desr.

// Creating a TypeToken for a List of Strings
Type listType = new TypeToken<List<String>>(){}.getType();

// Using it with Gson
List<String> strings = gson.fromJson(jsonString, listType);

Different Ways to Use TypeToken

  1. Simple Generic Types

  1. Nested Generic Types

  1. Custom Generic Classes

Creating Reusable TypeTokens

Advanced Usage with Parameterized Types

Working with Complex Nested Structures

Some points to consider -

  1. Insure proper type safety.

  2. Do proper error handling.

  3. Create type tokens and reuse them.

Last updated