Study/Spring Framework

[Spring] 객체에서 특정 필드 제외하고 직렬화/역직렬화 하기(@JsonIgnore, @JsonProperty)

jonghne 2023. 7. 19. 12:54

개요

자바 객체의 특정 필드를 제외하고 직렬화 / 역직렬화 해야 하는 경우 jackson 라이브러리의 @JsonIgnore 또는 @JsonProperty 어노테이션을 제외 시키고자 하는 필드 위에 추가하면 된다. 

 

@JsonIgnore : 해당 어노테이션을 붙인 객체의 필드는 직렬화 / 역직렬화 할 때 모두 해당 필드를 읽지 않게 하는 설정
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) : 해당 어노테이션을 붙인 필드는 직렬화 시에는 무시되지만, 역직렬화 시에는 해당 필드를 읽도록 하는 설정

 

@JsonIgnore

@JsonIgnore는 해당 어노테이션이 붙은 필드는 직력화 / 역직렬화 할 때 읽지 않는다.

 

아래는 CommentDto라는 객체를 ObjectMapper 를 통해 Map 형태로 직렬화할 때, data_seq라는 필드는 제외하도록 하는 예시이다. 

 

먼저 CommentDto의 무시하고자 하는 data_seq 필드 위에 @JsonIgnore 어노테이션을 붙인다. 

import lombok.Data;
import com.fasterxml.jackson.annotation.JsonIgnore;

@Data
public class CommentDto {
    @JsonIgnore
    private String data_seq;
    private String comment_seq;
    private String doc_id;
    private String doc_comment;
    private String co_id;
    private String user_id;
    private String dept_id;

 

그리고 ObjectMapper의 converValue 메서드를 통해 Map 형태로 직렬화 하면, data_seq 값은 제외하는 것을 확인할 수 있다.

	@Test
	public void getValidExcelDataTest() throws Exception {

		CommentDto commentDto = new CommentDto();
		commentDto.setData_seq("123");
		commentDto.setDoc_id("abc");

		Map<String,String> commentMap = objectMapper.convertValue(commentDto, Map.class);
		System.out.println(commentMap);
	}

 

반대로 Map 형태의 데이터를 CommentDto 객체로 역직려화 하는 경우에도, data_seq는 @JsonIgnore 애노테이션이 붙어져 있어서 읽지 않는다. 

	@Test
	public void getValidExcelDataTest() throws Exception {
		
		Map<String, Object> commentMap = new HashMap<>();
		commentMap.put("data_seq", "456");
		commentMap.put("doc_id", "def");
		CommentDto commentDtoCvt = objectMapper.convertValue(commentMap, CommentDto.class);
		System.out.println(commentDtoCvt);
	}

 

@JsonProperty

JsonProperty는 아래와 같이 WRITE_ONLY 속성을 추가하여 사용한다면, 객체를 직렬화 할 때는 필드를 읽지 않지만 반대로 객체로 역직렬화 하는 경우에는 필드를 읽는다. 

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class CommentDto {
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String data_seq;
    private String comment_seq;
    private String doc_id;
    private String doc_comment;
    private String co_id;
    private String user_id;
    private String dept_id;

}

 

그리고 JsonProperty는 이번 게시글에서 소개한 필드를 무시하는 옵션 외에도 필드 명을 다른 이름으로 바꾸게 하는 옵션도 있으니 참고 바란다

 

결론

상황에 맞게 객체의 특정 필드를 직렬화/역직렬화 할 때 모두 무시하고 싶다면 @JsonIgnore를 사용하면 되고,

만약 역직렬화 시에는 필드를 읽고 싶은 경우 JsonProperty을 사용하면 될 것 같다.