首页  

fastjson使用技巧     所属分类 fastjson 浏览量 2234
JSON.toJSONString  出现 $ref引用
全局设置
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();




序列化过滤指定字段
忽略异常字段

用 fastjson序列化展示 jmx 信息


        List memoryPools = ManagementFactory.getMemoryPoolMXBeans();
                
        for(MemoryPoolMXBean item:memoryPools){
        	System.out.println(item.getName()+","+item.getType()+","+item.getUsage()+","+item.getPeakUsage());
        	System.out.println(item.getCollectionUsageThreshold());
        	//System.out.println(item.getCollectionUsageThresholdCount());

        }        
        
getCollectionUsageThreshold() 报错   
java.lang.UnsupportedOperationException: CollectionUsage threshold is not supported
 
导致序列化失败 
使用 SerializerFeature.IgnoreErrorGetter ,忽略异常

输出很多无用字段信息 ,使用 PropertyFilter 过滤指定字段

import com.alibaba.fastjson.serializer.PropertyFilter;

public class JmxInfoPropertyFilter implements PropertyFilter{
	
	@Override  
    public boolean apply(Object object, String name, Object value) {  
        if(name.equalsIgnoreCase("objectName")){  
            return false;  
        }  
        if(name.equalsIgnoreCase("notificationInfo")){  
            return false;  
        }  
        if(name.equalsIgnoreCase("allThreadIds")){  
            return false;  
        }        
        return true;  
    } 

}

	
	public static String toJsonString(Object obj){		
		return JSON.toJSONString(obj,new JmxInfoPropertyFilter(),SerializerFeature.PrettyFormat,SerializerFeature.IgnoreErrorGetter);		
	}


SerializerFeature.DisableCircularReferenceDetect
SerializerFeature.PrettyFormat
SerializerFeature.IgnoreErrorGetter


Pet pet = new Pet("tiger",7,new Date());
str = JSON.toJSONString(pet, SerializerFeature.PrettyFormat,SerializerFeature.WriteClassName);

class dyyx.dto.Pet=tiger,3,Wed Jun 03 00:00:00 CST 2020,null
{
	"@type":"dyyx.dto.Pet",
	"weight":0.30000000000000004D,
	"name_":"tiger",
	"age":7,
	"birthdate":"20200603"
}

SerializerFeature.WriteClassName  自省 输出类名

上一篇     下一篇
tomcat8.5 jsp编译过程

XML解析之Digester

tomcat8.5启动过程调试

java获取当前jvm进程id

system.gc要点整理

String.intern要点整理