Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 JSON 직렬화 시 특정 필드를 무시하는 방법: @JsonIgnore 어노테이션 활용 가이드

Java 객체를 JSON으로 변환할 때 외부에 노출하고 싶지 않은 필드가 있을 수 있습니다. 이럴 때 Jackson 라이브러리에서 제공하는 @JsonIgnore 어노테이션을 사용하면 간단하게 해결할 수 있습니다.

@JsonIgnore 어노테이션이란?

@JsonIgnore는 클래스 내부의 특정 필드 수준(field level)에 적용할 수 있는 어노테이션으로, 직렬화(Serialization)역직렬화(Deserialization) 두 과정 모두에서 해당 필드를 무시하도록 지정합니다. 즉, 객체를 JSON으로 변환할 때 해당 필드는 출력에 포함되지 않으며, 반대로 JSON을 객체로 변환할 때도 해당 필드의 값은 매핑되지 않습니다.

문법(Syntax)

public @interface JsonIgnore

사용 예제

아래 예제는 Employee 클래스의 technologies 필드에 @JsonIgnore를 적용하여, 직렬화 결과에서 해당 필드가 어떻게 제외되는지 보여줍니다.

import java.io.*;
import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;

public class JsonIgnoreAnnotationTest {
    public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {
        Employee emp = new Employee();
        emp.setFirstName("Raja");
        emp.setLastName("Ramesh");
        emp.setEmpId(120);
        emp.getTechnologies().add("Java");
        emp.getTechnologies().add("Scala");
        emp.getTechnologies().add("Python");

        ObjectMapper mapper = new ObjectMapper();
        mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, emp);
    }
}

// Employee 클래스
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "firstName",
    "lastName",
    "technologies",
    "empId"
})
class Employee {

    @JsonProperty("EMPLOYEE_ID")
    private int empId;

    @JsonProperty("EMPLOYEE_FIRST_NAME")
    private String firstName;

    @JsonProperty("EMPLOYEE_LAST_NAME")
    private String lastName;

    @JsonIgnore
    private List<String> technologies = new ArrayList<>();

    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public List<String> getTechnologies() {
        return technologies;
    }
    public void setTechnologies(List<String> technologies) {
        this.technologies = technologies;
    }
}

실행 결과(Output)

@JsonIgnore가 적용된 technologies 필드가 출력 결과에서 완전히 제외된 것을 확인할 수 있습니다. 또한 @JsonProperty를 사용해 나머지 필드들은 지정한 커스텀 이름으로 직렬화되었습니다.

{
    "EMPLOYEE_FIRST_NAME" : "Raja",
    "EMPLOYEE_LAST_NAME" : "Ramesh",
    "EMPLOYEE_ID" : 120
}

참고: 다른 유용한 옵션들

여러 필드를 한 번에 무시해야 하는 경우에는 클래스 수준에서 @JsonIgnoreProperties({"필드1", "필드2"})를 사용할 수 있고, 역직렬화만 허용하고 직렬화는 막고 싶다면 @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)를 활용하는 방법도 있습니다. 상황에 맞는 어노테이션을 선택하면 더욱 유연하게 JSON 데이터를 제어할 수 있습니다.