Android org.json.* 没有实现Map 接口(interface),看起来很奇怪:
http://developer.android.com/reference/org/json/JSONObject.html
有人知道为什么吗?有一个简单的方法来解决这个问题,或者当我们碰巧使用 JSON 时,我们是否坚持使用一种特定的单独方法来导航一系列嵌套的 map ?
非常感谢 干杯>萨姆
最佳答案
我也很想知道为什么 Android 的 JSON 库没有实现标准接口(interface)......但无论如何,这是一种自己转换类型的方法:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class JsonHelper {
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)));
}
return map;
}
public static List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
for (int i = 0; i < array.length(); i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
private static Object fromJson(Object json) throws JSONException {
if (json instanceof JSONObject) {
return toMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
}
关于android - 为什么Android org.json.* 没有实现Map 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5566962/