How to deserialize a JSON array to list generic type in Java?


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]]
raja
Published on 09-Oct-2019 14:56:32
Advertisements