在网上查找了几个例子都不能成功,主要问题集中于JSONObject对象的遍历。网上多是使用net.sf.json.JSONObject.object.getSet()获取所有的key,但是在我的环境中,getSet()方法并不存在,需要强制转换object:((Map<String, Object>) object).getSet(),如此使用才不会报错,但是问题却又出现在强制转换上:JSONObject对象不允许转换为map类型:net.sf.json.JSONObject cannot be cast to java.util.Map。故而只能通过查询JSONObject对象的方法,写成用Iterator迭代的方法遍历key。

注:可能由于使用的类不同:我的环境:smartbi.net.sf.json.JSONObject; 网上是使用的:net.sf.json.JSONObject。

package shenji.suzhou.export;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import smartbi.net.sf.json.JSONArray;
import smartbi.net.sf.json.JSONObject;

public class OtherTest {
 public static void main(String[] args) {
  String jsonArrayData = "[{\"a1\":\"12\",\"b1\":\"112\",\"c1\":\"132\",\"d1\":\"134\"},{\"a2\":\"12\",\"b2\":\"112\",\"c2\":\"132\",\"d2\":\"134\"},{\"a3\":\"12\",\"b3\":\"112\",\"c3\":\"132\",\"d3\":\"134\"}]";
  JSONArray jsonArray = JSONArray.fromObject(jsonArrayData);
  toList(jsonArray);
 }

 /**
  * JSONObject转为map
  *
  * @param object
  *            json对象
  * @return 转化后的Map
  */
 public static Map<String, Object> toMap(JSONObject object) {
  Map<String, Object> map = new HashMap<String, Object>();
  Iterator it = object.keys();
  while (it.hasNext()) {
   String ss = it.next().toString();
   Object tt = object.get(ss);
   System.out.println(tt);
   map.put(ss, tt);
  }
  return map;
 }

 /**
  * JSONArray转为List
  *
  * @param array
  *            json数组
  * @return 转化后的List
  */
 public static List<Object> toList(JSONArray array) {
  List<Object> list = new ArrayList<Object>();
  for (int i = 0; i < array.length(); i++) {
   Object value = array.get(i);
   if (value instanceof JSONArray) {
    value = toList((JSONArray) value);
   }

   else if (value instanceof JSONObject) {
    value = toMap((JSONObject) value);
   }
   list.add(value);
  }
  return list;
 }
}