【fastJSON】利用fastJSON处理循环引用的问题

下载fastJSON jar   com.alibaba.fastjson

第一种:【写死的】

将需要序列化的字段传递进去,得到结果

//需要序列化的实体+字段
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Member.class,"字段1","字段2","可变字符串数组" );
        String result = JSON.toJSONString(Member.class, filter);

第二种:【可以复用灵活】

Map保存类对象+此对象所有的字段

传进来需要阻隔的字段

package net.shopxx.ws.utils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.serializer.PropertyFilter;

public class JSONExUtils implements PropertyFilter {
    
    //需要处理序列化阻隔的实体+实体所有的字段
    private Map<Class<?>, String[]> excludes = new HashMap<Class<?>, String[]>();
    
    /**
     * apply 方法 返回true表示需要序列化   
     * 参数2  不需要序列化的字段【属性】
     * 参数3  实体
     */
    @Override
    public boolean apply(Object object, String paramerter, Object entity) {
        //对象为NULL 直接放行
        if(entity == null){
             return true;
        }
        
        //获取需要序列化的 类对象
        Class<?> clazz = entity.getClass();
        
        //查找不需要序列化的字段
        for (Map.Entry<Class<?>, String[]> exItem : this.excludes.entrySet()) {
            // isAssignableFrom()  用来判断类型间是否有继承关系
            if(exItem.getKey().isAssignableFrom(clazz)){
                //不需要序列化的字段包含在所有字段中 下标>1   返回false
                return -1 != Arrays.binarySearch(exItem.getValue(), paramerter);
            }
        }
        return true;
    }
    
    public void setExcludes(Class<?> cls, String...properties) {
        excludes.put(cls, properties);
    }

    public Map<Class<?>, String[]> getExcludes() {
        return excludes;
    }

    public void setExcludes(Map<Class<?>, String[]> excludes) {
        this.excludes = excludes;
    }
    
    
    //获取本对象所有的属性  暂时没用
    public String[] just4Paramerters(Class<?> object){
        Field[] fields = object.getDeclaredFields();
        StringBuffer buffer = new StringBuffer();
        for (Field field : fields) {
            buffer.append(field.getName()+",");
        }
        if(buffer.length() > 0){
            String[] paramerters = buffer.toString().split(",");
            return paramerters;
        }
        return null;
    }
    
}

然后在需要使用的地方 调用即可!!

public void testName(){
        JSONExUtils exUtils = new JSONExUtils();
        exUtils.setExcludes(Member.class, new String[]{"需要阻隔的字段"});
        String result = JSON.toJSONString("", exUtils);
    }
原文地址:https://www.cnblogs.com/sxdcgaq8080/p/6478330.html