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

Tạo instance tùy chỉnh (Custom Instance Creator) bằng Gson trong Java

Khi parse JSON sang đối tượng Java, mặc định Gson thử tạo instance bằng default constructor. Nếu lớp Java không có default constructor hoặc cần cấu hình khởi tạo tùy chỉnh, cần tạo và đăng ký instance creator riêng.

Có thể tạo custom instance creator trong Gson dùng interface InstanceCreator và implement phương thức createInstance(Type type).

Cú pháp

T createInstance(Type type)

Ví dụ minh họa

import java.lang.reflect.Type;
import com.google.gson.*;

public class CustomInstanceCreatorTest {
    public static void main(String args[]) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Course.class, new CourseCreator());
        Gson gson = gsonBuilder.create();
        
        String jsonString = "{'course1':'Core Java', 'course2':'Advanced Java'}";
        Course course = gson.fromJson(jsonString, Course.class);
        System.out.println(course);
    }
}

// Lớp Course - KHÔNG có default constructor
class Course {
    private String course1;
    private String course2;
    private String technology;
    
    public Course(String technology) { // Chỉ có constructor có tham số
        this.technology = technology;
    }
    
    public void setCourse1(String course1) { this.course1 = course1; }
    public void setCourse2(String course2) { this.course2 = course2; }
    public String getCourse1() { return course1; }
    public String getCourse2() { return course2; } // Note: original code had bug returning course1
    public void setTechnology(String technology) { this.technology = technology; }
    public String getTechnology() { return technology; }
    
    public String toString() {
        return "Course[ " + "course1 = " + course1 + ", course2 = " + course2 + ", technology = " + technology + " ]";
    }
}

// Custom InstanceCreator
class CourseCreator implements InstanceCreator<Course> {
    @Override
    public Course createInstance(Type type) {
        Course course = new Course("Java"); // Khởi tạo với giá trị mặc định
        return course;
    }
}

Kết quả đầu ra

Course[ course1 = Core Java, course2 = Advanced Java, technology = Java ]

Lưu ý: InstanceCreator chỉ dùng cho deserialize (fromJson). Gson sẽ gọi createInstance() rồi dùng setter điền giá trị từ JSON. Pattern này hữu ích cho immutable objects hoặc class từ thư viện thứ 3 không thể sửa đổi constructor.