有没有发现json对象的不同内容?

时间:2013-05-13 09:20:18

标签: android json

有没有办法确定json对象的不同内容是什么?

它是否包含json数组?如果是,那json数组中是否有任何json对象?

2 个答案:

答案 0 :(得分:0)

是的,你当然可以做到这一点。 看一下JSONObject参考:

http://www.json.org/javadoc/org/json/JSONObject.html

您可以使用keys()迭代器来发现当前节点中可用的元素。

然后,您可以使用instanceof运算符检查某个节点是JSONArray还是String还是其他节点。

答案 1 :(得分:0)

试试这个

public void analyzeJSON(String jsonString) {
    JSONTokener tok = new JSONTokener(jsonString);
    while(tok.more()) {
        try {
            Object item = tok.nextValue();
            if (item instanceof JSONObject) {
                // JSON Object
                analyzeJSON(item.toString());
            } else if (item instanceof JSONArray) {
                // JSON Array
                JSONArray array = (JSONArray) item;
                for (int i = 0; i < array.length(); i++) {
                    Object subItem = array.get(i);
                    if (subItem instanceof JSONObject) {
                        // JSON Object
                        analyzeJSON(item.toString());
                    } else if (subItem instanceof JSONArray) {
                        // JSON Array inside array
                    } else {
                        // Something
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

希望这有帮助。