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
Simple Generic Types
Nested Generic Types
Custom Generic Classes
Creating Reusable TypeTokens
Advanced Usage with Parameterized Types
Working with Complex Nested Structures
Some points to consider -
Insure proper type safety.
Do proper error handling.
Create type tokens and reuse them.
Last updated