Gson 라이브러리의 @Expose 어노테이션은 객체의 특정 필드를 직렬화(serialization) 또는 역직렬화(deserialization) 과정에 포함시키거나 제외시킬 때 사용합니다. 이 어노테이션은 두 개의 boolean 파라미터를 가질 수 있으며, 각각 true 또는 false 값을 지정합니다.
주의할 점은 @Expose 어노테이션이 실제로 동작하도록 하려면 일반적인 방식으로 Gson 인스턴스를 생성해서는 안 되며, 반드시 GsonBuilder 클래스를 사용하고 excludeFieldsWithoutExposeAnnotation() 메서드를 호출해야 합니다. 이 메서드는 @Expose 어노테이션이 붙어 있지 않은 모든 필드를 직렬화 및 역직렬화 대상에서 제외하도록 Gson을 설정합니다.
문법(Syntax)
public GsonBuilder excludeFieldsWithoutExposeAnnotation()
예제 코드(Example)
import com.google.gson.*;
import com.google.gson.annotations.*;
public class JsonExcludeAnnotationTest {
public static void main(String args[]) {
Employee emp = new Employee("Raja", 28, 40000.00);
// @Expose 설정 없이 일반적으로 생성한 Gson 인스턴스
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonStr = gson.toJson(emp);
System.out.println(jsonStr);
// excludeFieldsWithoutExposeAnnotation()을 적용한 Gson 인스턴스
gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
jsonStr = gson.toJson(emp);
System.out.println(jsonStr);
}
}
// Employee 클래스
class Employee {
@Expose(serialize = true, deserialize = true)
public String name;
@Expose(serialize = true, deserialize = true)
public int age;
@Expose(serialize = false, deserialize = false)
public double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
}실행 결과(Output)
{
"name": "Raja",
"age": 28,
"salary": 40000.0
}
{
"name": "Raja",
"age": 28
}결과 분석
위 예제를 살펴보면 다음과 같은 차이를 확인할 수 있습니다.
- 첫 번째 출력: 일반적인 GsonBuilder로 생성한 인스턴스는 @Expose 어노테이션을 무시하므로 name, age, salary 세 필드가 모두 JSON에 포함됩니다.
- 두 번째 출력: excludeFieldsWithoutExposeAnnotation()이 적용된 인스턴스는 salary 필드가 serialize = false로 설정되어 있기 때문에 JSON 결과에서 제외되고, name과 age만 출력됩니다.
@Expose 어노테이션의 파라미터 조합을 정리하면 다음과 같습니다.
@Expose(serialize = true, deserialize = true): 직렬화와 역직렬화 모두에 포함@Expose(serialize = false, deserialize = false): 직렬화와 역직렬화 모두에서 제외@Expose(serialize = true, deserialize = false): 직렬화에만 포함(읽기 전용 출력)@Expose(serialize = false, deserialize = true): 역직렬화에만 포함(JSON 입력으로만 값 설정 가능)
이처럼 @Expose 어노테이션을 활용하면 비밀번호, 내부 계산용 값 등 민감하거나 불필요한 데이터가 외부로 노출되는 것을 손쉽게 방지할 수 있습니다.