ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Jackson Annotation 관련 정리 (업데이트 중)
    SPRING/SPRINGBOOT 2020. 8. 8. 17:39

    실무나 공부 중에 알게 된 Jackson Annotation 관련 사항에 대하여 정리를 하였다.

     

    @JsonIgnore

     

    해당 어노테이션을 사용하면 Jackson이 해당 프로퍼티를 무시하도록 만든다.

    예를 들어 아래와 같이 @JsonIgnore 어노테이션을 설정하면 Json으로 return할때 해당 필드들은 제외되게 된다.

    public class User {
    
        private Integer id;
        @Size(min=2, message ="Name은 2글자 이상 입력해 주세요.")
        private String name;
        @Past
        private Date joinDate;
    
        @JsonIgnore
        private String password;
        @JsonIgnore
        private String ssn;
    }
    

     

    @JsonIgnoreProperties

     

    @JsonIgnore와 같은 역할을 하지만, 한번에 여러개의 필드들을 무시하기 위해 사용한다.

    @JsonIgnoreProperties(value={"password", "ssn"}) 과 같은 형식으로 주로 class 위에 선언하여 사용된다.

     

     

    @JsonFilter

    클래스 레벨의 어노테이션으로 조건에 맞는 필드만 JSON으로 변환해야 할 때 사용하는 어노테이션이다.

    아래와 같이 Json으로 만들 필드들을 .fillOutAllExcept 메서드를 사용하여 설정하고,  addFillter 메서드를 사용하여 아래와 같이 filtering 할 수있다.

     

     

    위 스크린 샷과 같이 JsonFilter를 선언하여 사용할 수 있다.

    @GetMapping(value="/users/{id}", produces ="application/vnd.company.appv1+json")
    	public MappingJacksonValue retrieveUservV1(@PathVariable int id) {
    		User user =service.findOne(id);
    		if (user == null) {
    			throw new UserNotFoundException(String.format("ID[%s] not found", id));
    		}
     
    		SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter
    			.filterOutAllExcept("id","name","ssn");
    
    		FilterProvider filters = new SimpleFilterProvider().addFilter("UserInfo",filter);
    
    		MappingJacksonValue mapping = new MappingJacksonValue(user);
    		mapping.setFilters(filters);
    
    		return mapping;
    	}

     

Designed by Tistory.