Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 Gson으로 사용자 정의 인스턴스 생성기(InstanceCreator) 만드는 방법

Gson의 기본 객체 생성 방식

JSON 문자열을 Java 객체로 역직렬화하거나 그 반대 작업을 수행할 때, Gson은 기본적으로 해당 클래스의 기본 생성자(default constructor)를 호출하여 객체 인스턴스를 생성합니다.

그러나 다음과 같은 경우에는 기본 동작만으로는 원하는 결과를 얻을 수 없습니다.

  • Java 클래스에 기본 생성자가 정의되어 있지 않은 경우
  • 객체가 생성되는 시점에 특정 초기 설정(initial configuration)을 수행해야 하는 경우

이럴 때는 직접 인스턴스 생성기(instance creator)를 만들어 Gson에 등록해 주어야 합니다.

InstanceCreator 인터페이스란?

Gson에서는 InstanceCreator 인터페이스를 구현하여 사용자 정의 인스턴스 생성기를 만들 수 있습니다. 이 인터페이스는 createInstance(Type type) 메서드 하나만을 가지며, 이 메서드 안에서 원하는 방식으로 객체를 생성해 반환하면 됩니다.

문법(Syntax)

T createInstance(Type type)

예제 코드

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

// Course 클래스
class Course {
    private String course1;
    private String course2;
    private String technology;

    public Course(String technology) {
        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;
    }
    public void setTechnology(String technology) {
        this.technology = technology;
    }
    public String getTechnology() {
        return technology;
    }
    public String toString() {
        return "Course[ " +
                "course1 = " + course1 +
                ", course2 = " + course2 +
                ", technology = " + technology +
                " ]";
    }
}

// CourseCreator 클래스
class CourseCreator implements InstanceCreator<Course> {
    @Override
    public Course createInstance(Type type) {
        Course course = new Course("Java");
        return course;
    }
}

코드 설명

  • Course 클래스: 기본 생성자가 없으며, String 타입의 technology 매개변수를 받는 생성자만 존재합니다.
  • CourseCreator 클래스: InstanceCreator<Course>를 구현하며, createInstance() 메서드에서 technology 값을 "Java"로 초기화한 Course 객체를 생성해 반환합니다.
  • registerTypeAdapter(): GsonBuilder에 Course 클래스와 CourseCreator를 연결하여 등록합니다. 이후 Gson이 Course 객체를 생성해야 할 때마다 기본 생성자 대신 CourseCreator가 호출됩니다.

실행 결과(Output)

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

정리

기본 생성자가 없는 클래스나 객체 생성 시점에 초기화 로직이 필요한 경우, Gson의 InstanceCreator 인터페이스를 구현하고 registerTypeAdapter()로 등록하면 역직렬화 과정에서 객체가 원하는 방식으로 생성되도록 제어할 수 있습니다.