com.google.gson.JsonElement 클래스는 JSON 문서 내 하나의 요소를 나타냅니다. Gson 클래스가 제공하는 toJsonTree() 메서드를 사용하면 자바 객체를 JsonElement들의 트리 구조로 직렬화할 수 있습니다. 이렇게 만들어진 트리에서 getAsJsonObject() 메서드를 호출하면 해당 요소를 JsonObject 형태로 가져올 수 있으며, 여기에 addProperty()를 호출해 원하는 추가 속성을 손쉽게 삽입할 수 있습니다.
문법
public JsonObject getAsJsonObject()
이 메서드는 JsonElement를 JsonObject로 반환하며, 반환된 객체에 addProperty()를 사용해 새 키-값 쌍을 추가할 수 있습니다.
예제
아래 예제에서는 Student 객체를 먼저 JSON 문자열로 변환한 뒤, toJsonTree()로 트리 구조를 만들고 id라는 새로운 속성을 추가하여 다시 JSON 문자열로 출력합니다.
import com.google.gson.*;
public class AddPropertyGsonTest {
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // JSON 보기 좋게 출력
Student student = new Student("Adithya");
String jsonStr = gson.toJson(student, Student.class);
System.out.println("JSON 문자열: \n" + jsonStr);
JsonElement jsonElement = gson.toJsonTree(student);
jsonElement.getAsJsonObject().addProperty("id", "115");
jsonStr = gson.toJson(jsonElement);
System.out.println("추가 속성 삽입 후 JSON 문자열: \n" + jsonStr);
}
}
// Student 클래스
class Student {
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
출력 결과
JSON 문자열:
{
"name": "Adithya"
}
추가 속성 삽입 후 JSON 문자열:
{
"name": "Adithya",
"id": "115"
}
실행 결과를 보면 처음에는 name 필드만 담긴 JSON이 출력되지만, toJsonTree()로 생성한 JsonObject에 addProperty("id", "115")를 호출한 후 다시 직렬화하면 id 속성이 정상적으로 추가된 것을 확인할 수 있습니다. 이 방식은 객체 클래스를 수정하지 않고도 런타임에 동적으로 JSON 구조를 확장해야 할 때 특히 유용합니다.