通过setAllowNonStringKeys解决java.lang.ClassCastException: JSON keys must be strings

来源:互联网 发布:js需要做保护层吗 编辑:程序博客网 时间:2024/06/04 01:24

一直使用 json-lib-2.4-jdk15,感觉还不错, 通过 jsonConfig可以灵活性的设置参数

(吐槽下,这个jar 很久没有更新了)

 

今天使用的时候,报了个异常  java.lang.ClassCastException: JSON keys must be strings

 

代码片段如下 

 

Java代码  收藏代码
  1. LinkedHashMap<Integer, String> iteratorIndexMap = new LinkedHashMap<Integer, String>();  
  2. for (int i = startIteratorIndex; i <= endIteratorIndex; ++i){  
  3.     iteratorIndexMap.put(i, map.get(i));  
  4. }  
  5. pagerVMParam.setIteratorIndexMap(iteratorIndexMap);  
  6.   
  7. Map<String, Object> vmParamMap = new HashMap<String, Object>();  
  8. vmParamMap.put("pagerVMParam", pagerVMParam);  
  9. if (log.isDebugEnabled()){  
  10.     log.debug("vmParamMap:{}", JsonUtil.format(vmParamMap));  
  11.     log.debug("debugIsNotParseVM:{}", debugIsNotParseVM);  
  12. }  

 

 

因为我使用了 LinkedHashMap<Integer, String>, key是 integer类型的

 

 

网上已经有人给过解决方案:

http://hi.baidu.com/wsndbhs/item/1267fca7be8e989a151073b6

 

他的建议是 :

        修改Map的key为String.

 

        或者换jar包,换成低版本的!

 

 

我觉得不是最好的解决方案, 看了下这段源码:

Java代码  收藏代码
  1. if( !(k instanceof String) && !jsonConfig.isAllowNonStringKeys() ) {  
  2.    throw new ClassCastException("JSON keys must be strings.");  
  3. }  

 

可以通过 设置 setAllowNonStringKeys 来解决问题 ,下面是我封装的通用代码,来格式化输出对象为json格式, 方便我们debug代码或者记录日志

 

Java代码  收藏代码
  1. /** 
  2.  * Format. 
  3.  *  
  4.  * @param obj 
  5.  *            the obj 
  6.  * @param excludes 
  7.  *            the excludes 排除需要序列化成json的属性 
  8.  * @return the string 
  9.  */  
  10. public static String format(Object obj,String[] excludes){  
  11.     JsonConfig jsonConfig = new JsonConfig();  
  12.   
  13.     // 排除,避免循环引用 There is a cycle in the hierarchy!  
  14.     jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);  
  15.     jsonConfig.setIgnoreDefaultExcludes(true);  
  16.     jsonConfig.setAllowNonStringKeys(true);  
  17.   
  18.     if (Validator.isNotNullOrEmpty(excludes)){  
  19.         jsonConfig.setExcludes(excludes);  
  20.     }  
  21.     String string = JsonUtil.toJSON(obj, jsonConfig).toString(44);  
  22.     return string;  
  23. }  
0 0
原创粉丝点击