好多人在开发项目的时候遇到这样的情况,就是使用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类型的数据使用

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐