Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Deserialize mảng JSON thành List generic type trong Java bằng Gson

Thư viện Gson cung cấp lớp com.google.gson.reflect.TypeToken để lưu trữ các kiểu generic bằng cách tạo một lớp TypeToken của Gson và truyền kiểu lớp. Nhờ đó, Gson có thể biết lớp được truyền trong lớp generic.

Cú pháp

public class TypeToken<T> extends Object

Ví dụ minh họa

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);
    }
}

// Lớp Student
class Student {
    String name;
    String course;
    
    @Override
    public String toString() {
        return "Student [name=" + name + ", course=" + course + "]";
    }
}

Kết quả đầu ra

[Student [name=Adithya, course=Java], Student [name=Ravi, course=Python]]

Giải thích: Việc tạo new TypeToken<ArrayList<Student>>() {} là một anonymous inner class cho phép Gson giữ lại thông tin kiểu generic tại runtime (tránh type erasure). Đây là pattern tiêu chuẩn khi deserialize JSON array thành Collection generic.