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?

王林
Release: 2023-08-20 12:13:03
forward
1229 people have browsed it

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
Copy after login

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 + "]";
   }
}
Copy after login

Output

[Student [name=Adithya, course=Java], Student [name=Ravi, course=Python]]
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template