【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);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM