* 정적 필터링과 동적 필터링
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
//@JsonIgnoreProperties(value = {"filed1", "filed2"}) // static filtering
@JsonFilter("SomeBeanFilter")
public class SomeBean {
private String filed1;
//@JsonIgnore // static filtering
private String filed2;
private String filed3;
}
@RestController
public class FilteringController {
@GetMapping("/filtering")
public MappingJacksonValue filtering(){
SomeBean someBean = new SomeBean("value1", "value2", "value3");
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(someBean);
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("filed1", "filed3");
FilterProvider filters = new SimpleFilterProvider().addFilter("SomeBeanFilter", filter);
mappingJacksonValue.setFilters(filters);
return mappingJacksonValue;
}
@GetMapping("/filtering-list")
public MappingJacksonValue filteringList(){
List<SomeBean> list = Arrays.asList(
new SomeBean("value1", "value2", "value3"),
new SomeBean("value4", "value5", "value6")
);
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(list);
SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("filed2", "filed3");
FilterProvider filters = new SimpleFilterProvider().addFilter("SomeBeanFilter", filter);
mappingJacksonValue.setFilters(filters);
return mappingJacksonValue;
}
}
- @JsonIgnore 어노테이션은 특정 필드를 JSON 변환에서 제외할 때 사용됩니다.
- 예를 들어, 클래스의 특정 필드가 JSON으로 출력되지 않도록 하려면 해당 필드에 @JsonIgnore를 붙입니다.
- @JsonFilter 어노테이션은 필터의 이름을 지정하여 동적으로 필터를 적용할 수 있게 해줍니다.
- 필터의 이름은 컨트롤러에서 MappingJacksonValue와 함께 사용됩니다.
- SimpleFilterProvider는 MappingJacksonValue에 필터를 추가하기 위한 간단한 구현을 제공합니다.
- SimpleBeanPropertyFilter는 필터의 동작을 정의하는 데 사용됩니다.
- 위의 예제에서는 "fieldToExclude"를 제외한 모든 필드를 JSON으로 변환하도록 필터를 구성하고 있습니다. 필터의 동작은 프로젝트의 요구 사항에 따라 조정될 수 있습니다.
이러한 어노테이션과 필터를 사용하면 동일한 클래스를 여러 방식으로 JSON으로 변환하거나 특정 조건에 따라 필드를 제외하거나 포함시킬 수 있어, 유연한 JSON 변환을 할 수 있습니다.