转:json数据转换异常:net.sf.json.JSONException: java.lang.reflect.InvocationTargetException

执行:
JSONArray array = JSONArray.fromObject(this.users);

就会报以下错误:
net.sf.json.JSONException: java.lang.reflect.InvocationTargetException

users是一个list集合

 

方案一:

JSONArray array = JSONArray.fromObject(this.users.toArray()); 

方案二:

因为bean里有Date字段,且从数据库里读出来的是java.sql.Date赋值给了java.util.Date,转化成JSONArray时出错;可以在从数据库读出Date 时直接写成:new java.util.Date(rs.getDate("date").getTime),这样就不会出错了;

方案三:

 

  1. 日期格式
  2. hibernate延时加载

 

1.解决:日期格式

 
private java.util.Date createTime; 

 只在字段前声明Date的数据类型可能也会抛异常,在Set,get方法中,有出现Date类型的都把包名加上

 

2.解决:hibernate延时加载 设置

Java代码  收藏代码
  1. JsonConfig cfg = new JsonConfig();  
  2.   
  3. cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"});  

 

方法举例

Java代码  收藏代码
    1.                /** 
    2.  * datagrid easyui 查找出联系人pager-公共的,和自已创建的可以查看 
    3.  */  
    4. @Transactional(readOnly = true)  
    5. public JSONArray datagrid(Pager<AddressBook> page,User user,DetachedCriteria detachedCriteria){  
    6.     //有级联,不能直接转化,要取出List放到map里面  
    7.     JsonConfig cfg = new JsonConfig();  
    8.     //过滤关联,避免死循环net.sf.json.JSONException: java.lang.reflect.InvocationTargetException  
    9.     cfg.setJsonPropertyFilter(new PropertyFilter()  
    10.     {  
    11.          public boolean apply(Object source, String name, Object value) {  
    12.            if(name.equals("addressGroup")||name.equals("user")||name.equals("createTime")||name.equals("birthday")) {  
    13.              return true;  
    14.            } else {  
    15.              return false;  
    16.           }  
    17.         }  
    18.        });  
    19.     //net.sf.json.JSONException: java.lang.reflect.InvocationTargetException异常  
    20.    cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"});  
    21.     //javabean里出现循环调用啦,赶快用excludes干掉parent或者children   
    22.    // cfg.setExcludes(new String[]{"addressGroup"});   
    23.     //net.sf.json.JSONException: java.lang.reflect.InvocationTargetException日期格式转化出错  
    24.    // cfg.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);     
    25.     //cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd hh:mm:ss"));  
    26.       
    27.     Pager<AddressBook> pager=this.findAllByApprove(page, user, detachedCriteria);  
    28.     long total=pager.getTotalCount();  
    29.     List<AddressBook> list=pager.getResult();  
    30.     Map<String,Object> result=new HashMap<String,Object>();  
    31.     result.put("total", total);  
    32.     result.put("rows", list);  
    33.     JSONArray jsonArray  = JSONArray.fromObject(result,cfg);     
    34.     return jsonArray;  
    35.       
    36.       
    37. }  
posted on 2017-12-28 15:28  孤峰侠客  阅读(307)  评论(0编辑  收藏  举报