为什么Android org.json.*没有实现Map接口?

Sam*_*eph 2 android json interface map

Android org.json.*没有实现Map接口似乎很奇怪:

http://developer.android.com/reference/org/json/JSONObject.html

谁知道为什么?想一个简单的方法来解决这个问题,或者当我们碰巧使用JSON时,我们是否坚持使用一种特定的单独方式来导航一系列嵌套的地图?

非常感谢CHEERS> SAM

小智 5

我也很想知道为什么Android的JSON库没有实现标准接口......但无论如何,这是一种自己转换类型的方法:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)