JsonConfig 클래스는 직렬화(Serialization) 과정을 손쉽게 설정할 수 있도록 도와주는 유틸리티 클래스입니다. 이 클래스가 제공하는 setExcludes() 메서드를 사용하면 Bean 객체를 JSON 객체로 변환할 때 특정 속성(property)을 제외할 수 있습니다. 변환 시에는 JSONObject 클래스의 static 메서드인 fromObject()에 이 JsonConfig 인스턴스를 인자로 전달하면 됩니다.
문법(Syntax)
public void setExcludes(String[] excludes)
setExcludes() 메서드는 제외하고 싶은 속성 이름들을 문자열 배열 형태로 전달받습니다. 아래 예제에서는 Bean 객체를 JSON 객체로 변환하면서 일부 속성을 제외하는 방법을 확인할 수 있습니다.
예제(Example)
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class BeanToJsonExcludeTest {
public static void main(String[] args) {
Student student = new Student("Raja", "Ramesh", 35, "Madhapur");
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{"age", "address"});
JSONObject obj = JSONObject.fromObject(student, jsonConfig);
System.out.println(obj.toString(3)); // JSON 보기 좋게 출력
}
public static class Student {
private String firstName, lastName, address;
private int age;
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 String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
}
}위 예제에서는 Student 객체를 생성한 뒤 JsonConfig 인스턴스를 만들고, setExcludes() 메서드에 age와 address 속성을 전달하여 변환 과정에서 제외되도록 설정했습니다.
출력 결과(Output)
{
"firstName": "Raja",
"lastName": "Ramesh"
}출력 결과를 보면 age와 address 속성이 결과 JSON 객체에서 제외된 것을 확인할 수 있습니다. 이처럼 JsonConfig를 활용하면 민감한 정보나 불필요한 필드를 쉽게 걸러내고, 원하는 속성만 포함된 JSON 데이터를 깔끔하게 만들 수 있습니다.