Gson 사용자 정의 역직렬화란?
Gson 라이브러리는 기본 역직렬화 규칙만으로 처리하기 어려운 경우를 위해, GsonBuilder에 사용자 정의 역직렬화기(deserializer)를 등록하는 기능을 제공합니다. 이를 활용하면 JSON 데이터를 Java 객체로 변환하는 과정을 세밀하게 제어할 수 있습니다.
사용자 정의 역직렬화기를 만들려면 com.google.gson.JsonDeserializer 인터페이스를 구현하고 deserialize() 메서드를 재정의하면 됩니다.
아래 예제는 JSON 문자열의 password 필드를 Password 객체로 변환하는 사용자 정의 역직렬화 구현을 보여줍니다.
예제 코드
import java.lang.reflect.Type;
import com.google.gson.*;
public class CustomJSONDeSerializerTest {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Password.class, new PasswordDeserializer())
.setPrettyPrinting()
.create();
String jsonStr = "{" +
"\"firstName\": \"Adithya\"," +
"\"lastName\": \"Sai\"," +
"\"age\": 25," +
"\"address\": \"Pune\"," +
"\"password\": \"admin@123\"" +
"}";
Student student = gson.fromJson(jsonStr, Student.class);
System.out.println(student.getPassword().getPassword());
}
}
// 사용자 정의 역직렬화기
class PasswordDeserializer implements JsonDeserializer<Password> {
@Override
public Password deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
String encryptedPwd = json.getAsString();
return new Password(new StringBuffer(encryptedPwd).toString());
}
}
지원 클래스
// Student 클래스
class Student {
private String firstName;
private String lastName;
private int age;
private String address;
private Password password;
public Student(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
public Password getPassword() { return password; }
public void setPassword(Password password) { this.password = password; }
@Override
public String toString() {
return "Student[ firstName = " + firstName +
", lastName = " + lastName +
", age = " + age +
", address = " + address + " ]";
}
}
// Password 클래스
class Password {
private String password;
public Password(String password) {
super();
this.password = password;
}
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
실행 결과
admin@123
코드 동작 원리
- registerTypeAdapter(): GsonBuilder에 Password 타입 전용 역직렬화기인 PasswordDeserializer를 등록합니다.
- JsonDeserializer 구현: deserialize() 메서드 안에서 JSON 요소를 원하는 Java 객체로 변환하는 로직을 직접 작성할 수 있습니다.
- json.getAsString(): JSON 요소에서 문자열 값을 추출합니다.
- fromJson(): 역직렬화 중 password 필드를 만나면 일반적인 문자열 매핑 대신 등록된 PasswordDeserializer가 자동으로 호출됩니다.
사용자 정의 역직렬화가 필요한 경우
- 암호화된 필드(예: 비밀번호, 토큰)를 복호화해서 저장해야 할 때
- 서버가 반환하는 날짜·시간 형식이 표준 ISO 형식과 다를 때
- JSON 구조가 복잡하거나 값에 따라 파싱 방식이 달라져야 할 때
- 역직렬화 시점에 유효성 검증이나 기본값 설정이 필요할 때
이처럼 Gson의 사용자 정의 역직렬화기를 활용하면 복잡한 JSON 변환 로직도 하나의 클래스에 깔끔하게 캡슐화할 수 있어, 코드의 가독성과 유지보수성이 크게 향상됩니다.