使用json-lib转换对象为字符串时的特殊处理

使用json-lib转换对象为字符串时的特殊处理,如果属性名为"class", "declaringClass", "metaClass"只的一个

转换结果中不会包含该属性,示例

    public void test() {
        Map map = new HashMap(); 
        map.put( "class", "json" );  
        
        JSONObject jsonObject = JSONObject.fromObject( map ); 
        System.out.println( jsonObject );
    }

该方法的输出结果为 {}

解决办法,使用JsonConfig类对转换过程进行控制

    public void test() {
        Map map = new HashMap(); 
        map.put( "class", "json" ); 
        
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setIgnoreDefaultExcludes(true);

        JSONObject jsonObject = JSONObject.fromObject( map, jsonConfig ); 
        System.out.println( jsonObject );
    }

现在的输出结果为 {"class":"json"}

原文地址:https://www.cnblogs.com/xxt-mov/p/4335388.html