Flexjson은 자바 빈(Java Bean), 맵(Map), 배열(Array), 컬렉션(Collection) 등의 객체를 JSON 형식으로 직렬화(Serialize)하고 역직렬화(Deserialize)할 수 있는 경량급 자바 라이브러리입니다.
Flexjson의 핵심 클래스인 JSONSerializer는 자바 객체를 JSON으로 변환하는 직렬화 작업을 담당하며, 기본적으로 얕은 직렬화(shallow serialization) 방식으로 동작합니다. 만약 JSON 출력 결과를 사람이 읽기 쉽도록 들여쓰기와 줄바꿈이 적용된 형태로 만들고 싶다면, JSONSerializer 클래스가 제공하는 prettyPrint(boolean prettyPrint) 메서드를 사용하면 됩니다.
문법(Syntax)
public JSONSerializer prettyPrint(boolean prettyPrint)
prettyPrint 메서드에 true를 전달하면 JSON 문자열이 정렬되어 출력되고, false를 전달하거나 호출하지 않으면 기본적으로 한 줄로 압축된 형태로 출력됩니다.
예제 코드
아래 프로그램은 flexjson 라이브러리를 사용하여 JSON을 예쁘게(Pretty Print) 출력하는 예제입니다.
import flexjson.*;
public class PrettyPrintJSONTest {
public static void main(String[] args) {
// pretty print 활성화
JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
Employee emp = new Employee("Vamsi", "105", "Python Developer", "Python", "Pune");
String jsonStr = serializer.serialize(emp);
System.out.println(jsonStr);
}
}
// 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)
위 코드를 실행하면 다음과 같이 각 속성이 개별 줄에 정렬된, 가독성 높은 JSON 문자열이 출력됩니다.
{
"class": "Employee",
"designation": "Python Developer",
"id": "105",
"location": "Pune",
"name": "Vamsi",
"technology": "Python"
}이처럼 prettyPrint(true) 옵션 하나만 추가하면 별도의 포맷팅 작업 없이도 깔끔하게 정렬된 JSON을 손쉽게 얻을 수 있어, 로그 확인이나 디버깅 시 매우 유용합니다.