日期:2014-05-16  浏览次数:20499 次

json-lib 之jsonConfig详细使用(转)
一,setCycleDetectionStrategy 防止自包含

/**
     * 这里测试如果含有自包含的时候需要CycleDetectionStrategy
     */
    public static void testCycleObject() {
        CycleObject object = new CycleObject();
        object.setMemberId(\"yajuntest\");
        object.setSex(\"male\");
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

        JSONObject json = JSONObject.fromObject(object, jsonConfig);
        System.out.println(json);
    }

    public static void main(String[] args) {
               JsonTest.testCycleObject();
    }其中 CycleObject.java是我自己写的一个类:

public class CycleObject {

    private String      memberId;
    private String      sex;
    private CycleObject me = this;
…… // getters && setters
}
二,setExcludes:排除需要序列化成json的属性

public static void testExcludeProperites() {
        String str = \"{\'string\':\'JSON\', \'integer\': 1, \'double\': 2.0, \'boolean\': true}\";
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[] { \"double\", \"boolean\" });
        JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str, jsonConfig);
        System.out.println(jsonObject.getString(\"string\"));
        System.out.println(jsonObject.getInt(\"integer\"));
        System.out.println(jsonObject.has(\"double\"));
        System.out.println(jsonObject.has(\"boolean\"));
    }

    public static void main(String[] args) {
        JsonTest.testExcludeProperites();
    }
三,setIgnoreDefaultExcludes

@SuppressWarnings(\"unchecked\")
public static void testMap() {
Map map = new HashMap();
map.put(\"name\", \"json\");
map.put(\"class\", \"ddd\");
JsonConfig config = new JsonConfig();
config.setIgnoreDefaultExcludes(true);  //默认为false,即过滤默认的key
JSONObject jsonObject = JSONObject.fromObject(map,config);
System.out.println(jsonObject);

}
上面的代码会把name 和 class都输出。

而去掉setIgnoreDefaultExcludes(true)的话,就只会输出name,不会输出class。

   private static final String[] DEFAULT_EXCLUDES = new String[] { \"class\", \"declaringClass\",
         \"metaClass\" }; // 默认会过滤的几个key
四,registerJsonBeanProcessor 当value类型是从java的一个bean转化过来的时候,可以提供自定义处理器



public static void testMap() {
Map map = new HashMap();
map.put(\"name\", \"json\");
map.put(\"class\", \"ddd\");
map.put(\"date\", new Date());
JsonConfig config = new JsonConfig();
config.setIgnoreDefaultExcludes(false);
config.registerJsonBeanProcessor(Date.class,
new JsDateJsonBeanProcessor()); // 当输出时间格式时,采用和JS兼容的格式输出
JSONObject jsonObject = JSONObject.fromObject(map, config);
System.out.println(jsonObject);<