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
Creating Reusable TypeTokens
Advanced Usage with Parameterized Types
Working with Complex Nested Structures
Some points to consider -
Last updated