fastjson中使用SerializeFilter下的SimplePropertyPreFilter使用/忽略指定属性

接口按需序列化返回指定字段方式,可使用SerializeFilter下的SimplePropertyPreFilter配合注解实现。
getIncludes()保留字段
getExcludes()忽略字段

eg:
1、字段依赖注解

package cn.annotation;

import java.lang.annotation.*;

/**
 * 
 * @Date: 2022/04/20/10:04
 * @Description:
 */
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldDependent {
    /**
     * 依赖字段名
     * @return
     */
    String dependentName();

    /**
     *属性名
     * @return
     */
    String propertyName();
}

2、封装过滤器

package cn.filter;

import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

/**
 * 
 * @Date: 2022/04/20/10:49
 * @Description:
 */
@AllArgsConstructor
public class JsonPropertyPreFilter extends SimplePropertyPreFilter {

    /**
     * excludes 序列化时排除的属性
     *
     * @param filters
     * @return
     */
    public JsonPropertyPreFilter addExcludes(String... filters) {
        for (int i = 0; i < filters.length; i++) {
            this.getExcludes().add(filters[i]);
        }
        return this;
    }

    public JsonPropertyPreFilter addIncludes(String... filters) {
        for (int i = 0; i < filters.length; i++) {
            this.getIncludes().add(filters[i]);
        }
        return this;
    }
}

3、DTO类

package cn.dto;

import cn.annotation.FieldDependent;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Builder;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 
 * @Date: 2022/04/20/9:56
 * @Description:
 */
@Data
@Builder
public class TestDto {
    public static final Map<String, List<String>> FIELD_DEPENDENT;

    static {
        Field[] declaredFields = TestDto.class.getDeclaredFields();
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (Field field : declaredFields) {
            FieldDependent declaredAnnotation = field.getDeclaredAnnotation(FieldDependent.class);
            if (declaredAnnotation != null) {
                map.putIfAbsent(declaredAnnotation.dependentName(), new ArrayList<String>());
                map.get(declaredAnnotation.dependentName()).add(declaredAnnotation.propertyName());
            }
        }
        FIELD_DEPENDENT = Collections.unmodifiableMap(map);
    }

    /**
     * 姓名
     */
    @FieldDependent(dependentName = "Name", propertyName = "name")
    @JSONField(name = "name")
    private String name;
    /**
     * 年龄
     */
    @FieldDependent(dependentName = "Age", propertyName = "age")
    @JSONField(name = "age")
    private Integer age;
    /**
     * 职业
     */
    @JSONField(name = "occupation")
    @FieldDependent(dependentName = "Occupation", propertyName = "occupation")
    private String occupation;
}
package cn.dto;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ResContent implements Serializable {
    
    /**
     * 内容
     */
    @JSONField(jsonDirect=true)
    private String content;
}

测试

package com.test;

import cn.dto.ResContent;
import cn.dto.TestDto;
import cn.filter.JsonPropertyPreFilter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.*;

/**
 * 
 * @Date: 2022/04/20/10:32
 * @Description:
 */
@Slf4j
public class JsonTest {
    @Test
    public void JsonTestNOne(){
        TestDto iverSen = TestDto.builder().name("Iversen").age(22).occupation("software engineer").build();
        //eg:自定义展示字段/从权限系统获取配置的字段列表
        Set<String> fields = this.getFilelds();
        List<String> excludeProperties = new ArrayList<>();
        Map<String, List<String>> fieldDependent = TestDto.FIELD_DEPENDENT;
        for (Map.Entry<String,List<String>> entry: fieldDependent.entrySet()) {
            if (!fields.contains(entry.getKey())){
                excludeProperties.addAll(entry.getValue());
            }
        }

        JsonPropertyPreFilter jsonPropertyPreFilter = new JsonPropertyPreFilter();
        jsonPropertyPreFilter.addExcludes(excludeProperties.toArray(new String[0]));

        String jsonString = JSON.toJSONString(iverSen, jsonPropertyPreFilter, SerializerFeature.WriteMapNullValue);
        log.info("json序列化之后的结果:{}",jsonString);
        ResContent build = ResContent.builder().content(jsonString).build();
        JSONObject jsonObject = JSON.parseObject(build.getContent());
        log.info("JSONObject:{}",jsonObject);
    }

    private Set<String> getFilelds() {
        //eg:只展示姓名职业,忽略年龄
        Set<String> setResult = new HashSet<>();
        setResult.add("Name");
        setResult.add("Occupation");
        return setResult;
    }
}

结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值