一直使用 json-lib-2.4-jdk15,感觉还不错, 通过 jsonConfig可以灵活性的设置参数
(吐槽下,这个jar 很久没有更新了)
?
今天使用的时候,报了个异常 ?java.lang.ClassCastException: JSON keys must be strings
?
代码片段如下?
?
			LinkedHashMap<Integer, String> iteratorIndexMap = new LinkedHashMap<Integer, String>();
			for (int i = startIteratorIndex; i <= endIteratorIndex; ++i){
				iteratorIndexMap.put(i, map.get(i));
			}
			pagerVMParam.setIteratorIndexMap(iteratorIndexMap);
			Map<String, Object> vmParamMap = new HashMap<String, Object>();
			vmParamMap.put("pagerVMParam", pagerVMParam);
			if (log.isDebugEnabled()){
				log.debug("vmParamMap:{}", JsonUtil.format(vmParamMap));
				log.debug("debugIsNotParseVM:{}", debugIsNotParseVM);
			}
?
?
因为我使用了 LinkedHashMap<Integer, String>, key是 integer类型的
?
?
网上已经有人给过解决方案:
http://hi.baidu.com/wsndbhs/item/1267fca7be8e989a151073b6
?
他的建议是 :
? ? ? ? 修改Map的key为String.
?
? ? ? ? 或者换jar包,换成低版本的!
?
?
我觉得不是最好的解决方案, 看了下这段源码:
            if( !(k instanceof String) && !jsonConfig.isAllowNonStringKeys() ) {
               throw new ClassCastException("JSON keys must be strings.");
            }
?
可以通过 设置?setAllowNonStringKeys 来解决问题 ,下面是我封装的通用代码,来格式化输出对象为json格式, 方便我们debug代码或者记录日志
?
	/**
	 * Format.
	 * 
	 * @param obj
	 *            the obj
	 * @param excludes
	 *            the excludes 排除需要序列化成json的属性
	 * @return the string
	 */
	public static String format(Object obj,String[] excludes){
		JsonConfig jsonConfig = new JsonConfig();
		// 排除,避免循环引用 There is a cycle in the hierarchy!
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		jsonConfig.setIgnoreDefaultExcludes(true);
		jsonConfig.setAllowNonStringKeys(true);
		if (Validator.isNotNullOrEmpty(excludes)){
			jsonConfig.setExcludes(excludes);
		}
		String string = JsonUtil.toJSON(obj, jsonConfig).toString(4, 4);
		return string;
	}
?
