通过http请求得到了一个json数组就是[{},{}]形式,怎么把这个数组转换成java类中可以处理对象啊,数组或者集合?麻烦指点下,折腾一晚上了,我用的json-lib和http://johncon.javaeye.com/blog/250788里面的通用类,因为首次接触到这方面东西,所以请高手详细指点下。

解决方案 »

  1.   

    我想可以这么做
    先用正则把外面的中括号去掉
    然后计算大括号的对数(计算个数除2)
    大括号的对数就是数组的大小
    然后判断大括号中的类型
    大括号中的类型就是数组的类型
    最后按照判断出来的结果 new一个数组
      

  2.   


    /** 
       * 从一个JSON数组得到一个java对象数组,形如: 
       * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...] 
       * @param object 
       * @param clazz 
       * @return 
       */  
       public static Object[] getDTOArray(String jsonString, Class clazz){  
            setDataFormat2JAVA();  
            JSONArray array = JSONArray.fromObject(jsonString);  
           Object[] obj = new Object[array.size()];  
                for(int i = 0; i < array.size(); i++){  
                     JSONObject jsonObject = array.getJSONObject(i);  
                    obj[i] = JSONObject.toBean(jsonObject, clazz);  
                }  
                return obj;  
      }  
    这个方法感觉能实现我的需求,但是我调用总会出现
    java.lang.NoSuchMethodError: org.apache.commons.collections.map.ListOrderedMap: method <init>()V not found
    net.sf.json.JSONObject.<init>(JSONObject.java:1553)
    net.sf.json.util.CycleDetectionStrategy.<clinit>(CycleDetectionStrategy.java:37)
    net.sf.json.JsonConfig.<clinit>(JsonConfig.java:64)
    net.sf.json.JSONArray.fromObject(JSONArray.java:129)
    net.hialex.fanfou.util.JsonUtil.getDTOList(JsonUtil.java:119)
    net.hialex.fanfou.util.Fanfou.randomBrowse(Fanfou.java:88)
    net.hialex.fanfou.servlet.randomBrowse.doGet(randomBrowse.java:19)
    net.hialex.fanfou.servlet.randomBrowse.doPost(randomBrowse.java:23)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    不知道是什么情况,可能是我调用的有问题,getDTOArray(String jsonString, Class clazz)中的clazz我不知道该如何调用
      

  3.   

    json-lib依赖apache common-collections等包,所以需要去下.
    你可以可以用没有外部依赖的JSON.simple:
    http://code.google.com/p/json-simple/