spring boot json 属性动态过滤 完美解决 兼容原生 @ResponseBody @JsonIgnoreProperties @JsonView
先说说环境是spring boot 2.1x版本 其他版本都是一样。
说说关键点在哪,主要是com.fasterxml.jackson.databind.ObjectMapper这个类在spring框架里是单独的,所以我们要想法把动态过滤的时候做一个拷贝出来,但是尽量不要破坏spring的程序流程和结构。
第一步 我们先要截取Controller定义的注解,这个类只需要被spring扫描到就可以执行
@ControllerAdvice
public class JFilterResponseBodyAdvice extends AbstractMappingJacksonResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return super.supports(returnType, converterType) && ( returnType.hasMethodAnnotation(JFilters.class) || returnType.hasMethodAnnotation(JFilter.class) );
}
protected MappingJacksonValue getOrCreateContainer(Object body) {
return (body instanceof MappingJacksonValue ? (MappingJacksonValue) body : new JFilterValue(body));
}
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
MethodParameter returnType, ServerHttpRequest request,
ServerHttpResponse response) {
if (returnType.hasMethodAnnotation(JFilters.class)) {
((JFilterValue) bodyContainer).setJfilters(returnType.getMethodAnnotation(JFilters.class).value());
} else if (returnType.hasMethodAnnotation(JFilter.class)) {
((JFilterValue) bodyContainer).setJfilters(
new JFilter[]{returnType.getMethodAnnotation(JFilter.class)}
);
}
}
}
第二步 我们需要把接受到的过滤信息存储到MappingJacksonValue