Wisdom
  • Welcome
  • core
    • Flyway
    • Bean Validation
    • Lombok
    • Webclient
      • Generic Webclient Api
      • SSL Certificate
    • Application Event Publisher
    • REST API's Design
      • Http Methods and Status Codes
      • Resource Naming and URL Structure
      • Request / Response Design
      • Versioning Strategies
      • Filtering and Searching In API
    • Spring Boot Mail Integration
      • Sendgrid
    • Template Engines
      • Java Template Engine [JTE]
  • security
    • Complete Guide to URL Matchers in Spring Security: Types, Examples, Pros, Cons, and Best Use Cases
    • Passwordless Login With Spring Security 6
      • Spring Security OneTimeToken
        • One Time Token with default configuration
        • One Time Token with custom configuration
        • One Time Token With Jwt
  • others
    • How to Integrate WhatsApp for Sending Messages in Your Application
  • java
    • Interview Questions
      • Constructor
      • Serialization
      • Abstract Class
    • GSON
      • Type Token
      • Joda Datetime Custom Serializer and Deserializer
  • Nginx
    • Core Concepts and Basics
    • Deep Dive on NGINX Configuration Blocks
    • Deep Dive on NGINX Directives
    • Deep Dive into Nginx Variables
    • Nginx as a Reverse Proxy and Load Balancer
    • Security Hardening in NGINX
    • Performance Optimization & Tuning in NGINX
    • Dynamic DNS Resolution in Nginx
    • Advanced Configuration & Use Cases in NGINX
    • Streaming & Media Delivery in NGINX
    • Final Configuration
  • Angular
    • How to Open a PDF or an Image in Angular Without Dependencies
    • Displaying Colored Logs with Search Highlighting in Angular 6
    • Implementing Auto-Suggestion in Input Field in Angular Template-Driven Forms
    • Creating an Angular Project Using npx Without Installing It Globally
    • Skip SCSS and Test Files in Angular with ng generate
  • Javascript
    • When JavaScript's Set Falls Short for Ensuring Uniqueness in Arrays of Objects
    • Demonstrating a Function to Get the Last N Months in JavaScript
    • How to Convert Numbers to Words in the Indian Numbering System Using JavaScript
    • Sorting Based on Multiple Criteria
  • TYPESCRIPT
    • Using Omit in TypeScript
Powered by GitBook
On this page
  • Problem That TypeToken solves
  • Different Ways to Use TypeToken
  • Creating Reusable TypeTokens
  • Advanced Usage with Parameterized Types
  • Working with Complex Nested Structures
  • Some points to consider -
  1. java
  2. GSON

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

// For List<String>
Type stringListType = new TypeToken<List<String>>(){}.getType();

// For Set<Integer>
Type integerSetType = new TypeToken<Set<Integer>>(){}.getType();

// For Map<String, Boolean>
Type mapType = new TypeToken<Map<String, Boolean>>(){}.getType();
  1. Nested Generic Types

// For List<List<String>>
Type nestedListType = new TypeToken<List<List<String>>>(){}.getType();

// For Map<String, List<User>>
Type complexMapType = new TypeToken<Map<String, List<User>>>(){}.getType();
  1. Custom Generic Classes

// Generic response wrapper
public class ApiResponse<T> {
    private int status;
    private T data;
    // getters and setters
}

// Usage
Type responseType = new TypeToken<ApiResponse<User>>(){}.getType();
ApiResponse<User> response = gson.fromJson(json, responseType);

Creating Reusable TypeTokens

public class TypeTokens {
    // Private constructor to prevent instantiation
    private TypeTokens() {}
    
    // Reusable TypeToken for List<String>
    public static final Type STRING_LIST_TYPE = new TypeToken<List<String>>(){}.getType();
    
    // Reusable TypeToken for Map<String, User>
    public static final Type STRING_USER_MAP_TYPE = new TypeToken<Map<String, User>>(){}.getType();
}

// Usage
List<String> strings = gson.fromJson(json, TypeTokens.STRING_LIST_TYPE);

Advanced Usage with Parameterized Types

public class GenericTypeHandler<T> {
    private final Type type;

    public GenericTypeHandler() {
        // Capture the actual type parameter
        Type superclass = getClass().getGenericSuperclass();
        if (superclass instanceof ParameterizedType) {
            this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
        } else {
            throw new RuntimeException("Missing type parameter.");
        }
    }

    public T fromJson(String json) {
        return new Gson().fromJson(json, type);
    }
}

// Usage
public class UserListHandler extends GenericTypeHandler<List<User>> {}

UserListHandler handler = new UserListHandler();
List<User> users = handler.fromJson(jsonString);

Working with Complex Nested Structures

public class ComplexTypeExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        
        // Complex nested structure
        Type complexType = new TypeToken<Map<String, List<Set<User>>>>(){}.getType();
        
        // Creating sample data
        Map<String, List<Set<User>>> data = new HashMap<>();
        // ... populate data ...
        
        // Serialization
        String json = gson.toJson(data, complexType);
        
        // Deserialization
        Map<String, List<Set<User>>> parsed = gson.fromJson(json, complexType);
    }
}

Some points to consider -

  1. Insure proper type safety.

  2. Do proper error handling.

  3. Create type tokens and reuse them.

PreviousGSONNextJoda Datetime Custom Serializer and Deserializer

Last updated 4 months ago