- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to serialize and de-serialize generic types using the Gson library in Java?\n
If a Java class is a generic type and we are using it with the Gson library for JSON serialization and deserialization. The Gson library provides a class called com.google.gson.reflect.TypeToken to store generic types by creating a Gson TypeToken class and pass the class type. Using this type, Gson can able to know the class passed in the generic class.
Syntax
public class TypeToken<T> extends java.lang.Object
Example
import java.lang.reflect.Type; import java.util.*; import com.google.gson.*; import com.google.gson.reflect.*; public class GenericTypesJSONTest { public static void main(String[] args) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); List<String> list = Arrays.asList("INDIA", "AUSTRALIA", "ENGLAND", "SOUTH AFRICA"); String jsonStr = gson.toJson(list); System.out.println(jsonStr); Type listType = new TypeToken<List<String>>() {}.getType(); list = gson.fromJson(jsonStr, listType); System.out.println(list); } }
Output
[ "INDIA", "AUSTRALIA", "ENGLAND", "SOUTH AFRICA" ] [INDIA, AUSTRALIA, ENGLAND, SOUTH AFRICA]
Advertisements