The Gson library provides a class named com.google.gson.reflect.TypeToken to store generic types by creating a Gson TypeToken class and passing the class type. Using this type, Gson can know the class passed in the generic class.
public class TypeToken<T> extends Object
We can deserialize a JSON array into a list of generic types in the example below
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 + "]"; } }
[Student [name=Adithya, course=Java], Student [name=Ravi, course=Python]]
The above is the detailed content of How to deserialize JSON array to generic type of list in Java?. For more information, please follow other related articles on the PHP Chinese website!