Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 deserialize a JSON array to list generic type in Java?\\n
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 Object
We can deserialize a JSON array to a generic type of list in the below example
Example
import java.lang.reflect.Type;
import java.util.*;
import com.google.gson.*;
import com.google.gson.reflect.*;
public class JSONArrayToListTest {
public static void main(String args[]) throws Exception {
String jsonStr = "[{\"name\":\"Adithya\", \"course\":\"Java\"}," + "{\"name\":\"Ravi\", \"course\":\"Python\"}]";
Type listType = new TypeToken<ArrayList<Student>>() {}.getType();
List<Student> students = new Gson().fromJson(jsonStr, listType);
System.out.println(students);
}
}
// Student class
class Student {
String name;
String course;
@Override
public String toString() {
return "Student [name=" + name + ", course=" + course + "]";
}
}
Output
[Student [name=Adithya, course=Java], Student [name=Ravi, course=Python]]
Advertisements