Jackson 라이브러리의 @JsonIgnoreType 어노테이션을 사용하면 직렬화(Serialization) 과정에서 특정 클래스 전체를 무시할 수 있습니다. 이 어노테이션이 적용된 클래스는 JSON 객체를 직렬화하거나 역직렬화할 때 해당 클래스의 모든 속성과 필드가 함께 제외됩니다.
예를 들어, Employee(직원) 클래스 안에 Address(주소) 클래스가 포함되어 있고, Address 정보는 JSON 출력에서 제외하고 싶다면 Address 클래스에 @JsonIgnoreType을 선언하기만 하면 됩니다. 그러면 Employee 객체를 직렬화할 때 empAddress 필드가 자동으로 생략됩니다.
@JsonIgnoreType 문법
@Target(value={ANNOTATION_TYPE,TYPE})
@Retention(value=RUNTIME)
public @interface JsonIgnoreType@JsonIgnoreType 사용 예제
아래 예제는 Employee 클래스의 내부 static 클래스인 Address에 @JsonIgnoreType을 적용한 코드입니다. ObjectMapper로 객체를 JSON 문자열로 변환하면 Address 관련 필드는 결과에 포함되지 않습니다.
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class JsonIgnoreTypeTest {
public static void main(String args[]) throws IOException {
Employee emp = new Employee();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
System.out.println(jsonString);
}
}
// Employee 클래스
class Employee {
@JsonIgnoreType
public static class Address {
public String firstLine = null;
public String secondLine = null;
public String thirdLine = null;
@Override
public String toString() {
return "Address{" +
"firstLine='" + firstLine + '\'' +
", secondLine='" + secondLine + '\'' +
", thirdLine='" + thirdLine + '\'' +
'}';
}
} // Address 클래스 끝
public long empId = 115;
public String empName = "Raja Ramesh";
public Address empAddress = new Address();
@Override
public String toString() {
return "Employee{" +
"empId=" + empId +
", empName='" + empName + '\'' +
", empAddress=" + empAddress +
'}';
}
}실행 결과
실행 결과를 보면 empId와 empName만 JSON에 포함되고, @JsonIgnoreType이 적용된 Address 타입의 empAddress 필드는 완전히 제외된 것을 확인할 수 있습니다.
{
"empId" : 115,
"empName" : "Raja Ramesh"
}@JsonIgnoreType과 @JsonIgnore의 차이점
@JsonIgnore는 개별 속성이나 필드 하나씩만 무시할 때 사용하는 반면, @JsonIgnoreType은 특정 타입(클래스) 자체를 지정하여 그 타입을 가진 모든 속성을 한 번에 제외할 수 있다는 점이 큰 차이입니다. 따라서 여러 곳에서 재사용되는 클래스(예: Address, AuditInfo 등)를 일괄적으로 직렬화 대상에서 제외해야 할 때 매우 유용합니다.