好多人在开发项目的时候遇到这样的情况,就是使用SSH框架的时候,在使用JSONArray.fromObject()时候出现net.sf.json.JSONException: java.lang.reflect.InvocationTargetException异常,这种情况的出现是由于Date类型转换或是延迟加载,这里不解释过多,说一下解决办法:
方法一:过滤关联,使用JsonConfig的setExcludes()方法排除可能造成这种情况的数据项
JsonConfig cfg = new JsonConfig(); //过滤关联,避免死循环net.sf.json.JSONException: java.lang.reflect.InvocationTargetException cfg.setJsonPropertyFilter(new PropertyFilter(){ public boolean apply(Object source,String name,Object value){ if(name.equals("preOrderRoomDetailSet")||name.equals("preArriveTime")||name.equals("preLeaveTime")||name.equals("orderTime")){ return true; } else{ return false;} } }); cfg.setExcludes(new String[]{"preOrderRoomDetailSet","preArriveTime","preLeaveTime","orderTime"}); cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"}); cfg.setIgnoreDefaultExcludes(false); cfg.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);*/ //cfg.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor(datePattern)); /*Map<String,Object>map=new HashMap<String,Object>(); map.put("total",count);//保存查询出记录的条数 if(list!=null){ map.put("rows",list);//保存查询出记录的详细信息 } return JSONArray.fromObject(map,cfg).toString();
方法二:这种情况一般是在方法一失效的情况,这是很烦人的,只能自己拼json形式的字符串
int count = this.preOrderRoomDao.findRecordCount(sqlSignal,param); List<PreOrderRoom> list = this.preOrderRoomDao.getPreOrderRecordBySearch(sqlSignal,param); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("'total':"+count+",'rows':[ "); for (int i = 0;i<list.size(); i++){ sb.append("{'preOrderID':'" + list.get(i).getPreOrderID() + "','customerName':'" + list.get(i).getCustomerName() + "','customerPhone':'" + list.get(i).getCustomerPhone() + "','certificateNumber':'" + list.get(i).getCertificateNumber() + "','preArriveTime':'" + sdf.format(list.get(i).getPreArriveTime().getTime()) + "','preOrderStatus':'" + list.get(i).getPreOrderStatus() + "'}"); if (i != list.size()-1){ sb.append(",");} } sb.append("] }"); return sb.toString(); }catch(Exception e){ logger.debug(e.getMessage()); }
返回的仍然是json格式的数据,使用时仍然可以按json类型的数据使用 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|