Home >Java >javaTutorial >How to deserialize JSON array to generic type of list in Java?

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

王林
王林forward
2023-08-20 12:13:031228browse

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

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.

Syntax

public class TypeToken<T> extends Object

We can deserialize a JSON array into a list of generic types in the example below

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]]

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete