android - 为什么Android org.json.* 没有实现Map 接口(interface)?

标签 android json interface dictionary

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/

相关文章:

android - 使用 ViewModel 的接口(interface)?

c# - 在派生对象中使用比父对象定义的类型更强的列表

c# - 这是 C# Monad,问题出在哪里?

java - 我如何从Android中的毫秒数中获取一天中的小时数

android - Phonegap/Genymotion 的困难

c# - BotFramework - 使用 Json 模式定义表单 - 如何访问 OnCompletion 方法中的表单字段?

java - 为循环优化 JSonArray

android - 构建新项目时出错 - aapt 已完成,退出值非零 1

java - 使用 jsoup 连接到 URL 时出现异常

javascript - 如何在 Reactjs 的菜单中设置 onClick 函数?