我写了这些代码几天回来通过递归。
public static Map jsonToMap(JSONObject json) throws JSONException {
Map retMap = new HashMap();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
public static Map toMap(JSONObject object) throws JSONException {
Map map = new HashMap();
Iterator keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
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;
}