Gson은 Google에서 개발한 Java용 JSON 라이브러리입니다. Gson을 사용하면 Java 객체를 JSON으로 생성(직렬화)하거나, 반대로 JSON을 Java 객체로 변환(역직렬화)할 수 있습니다.
기본적으로 Gson은 줄바꿈이나 들여쓰기 없이 압축된 형태(compact format)로 JSON을 출력합니다. 하지만 로그 확인이나 디버깅 시에는 사람이 읽기 쉬운 형태의 JSON이 훨씬 유용합니다. 이때 Gson pretty print(예쁘게 출력) 기능을 활성화하면 됩니다.
Pretty printing을 사용하려면 GsonBuilder 클래스의 setPrettyPrinting() 메서드를 호출하여 Gson 인스턴스를 설정해야 합니다. 이 메서드는 JSON 출력 시 페이지에 보기 좋게 정렬된 형태로 출력되도록 Gson을 구성합니다.
문법(Syntax)
public GsonBuilder setPrettyPrinting()
사용 예제(Example)
아래 예제는 Employee 객체를 생성하고, setPrettyPrinting()이 적용된 Gson 인스턴스를 통해 예쁘게 출력된 JSON 문자열을 콘솔에 출력하는 코드입니다.
import java.util.*;
import com.google.gson.*;
public class PrettyJSONTest {
public static void main(String[] args) {
Employee emp = new Employee("Raja", "115", "Content Engineer", "Java", "Hyderabad");
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print 적용
String prettyJson = gson.toJson(emp);
System.out.println(prettyJson);
}
}
// Employee 클래스
class Employee {
private String name, id, designation, technology, location;
public Employee(String name, String id, String designation, String technology, String location) {
super();
this.name = name;
this.id = id;
this.designation = designation;
this.technology = technology;
this.location = location;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public String getDesignation() {
return designation;
}
public String getTechnology() {
return technology;
}
public String getLocation() {
return location;
}
}실행 결과(Output)
setPrettyPrinting() 메서드를 적용하면 다음과 같이 각 필드가 줄바꿈과 들여쓰기로 정렬된 가독성 높은 JSON이 출력됩니다.
{
"name": "Raja",
"id": "115",
"designation": "Content Engineer",
"technology": "Java",
"location": "Hyderabad"
}정리
Gson의 기본 출력 형식은 공간을 절약하는 압축(compact) 방식입니다. 따라서 개발 중 디버깅이나 로그 분석을 위해서는 new GsonBuilder().setPrettyPrinting().create()를 사용하여 가독성 좋은 JSON 출력을 활용하는 것이 좋습니다. 반대로 운영 환경에서 데이터 전송 용량을 줄여야 하는 경우에는 기본 압축 형식을 그대로 사용하는 것이 효율적입니다.