spring boot json 动态过滤属性 自定义标签 完美解决 兼容原生 @ResponseBody @JsonIgnoreProperties @JsonView

本文介绍了如何在Spring Boot 2.1.x版本中实现JSON属性的动态过滤,同时保持与原生`@ResponseBody`、`@JsonIgnoreProperties`和`@JsonView`的兼容。通过截取Controller的注解,存储过滤信息,并在Jackson输出前创建ObjectMapper副本进行过滤操作。详细步骤包括创建拦截器、修改`writeInternal`方法以应用自定义过滤规则,并实例化过滤器Bean。
摘要由CSDN通过智能技术生成

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值