首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在JSONObject上迭代?

如何在JSONObject上迭代?
EN

Stack Overflow用户
提问于 2012-02-06 02:06:17
回答 16查看 682.7K关注 0票数 374

我使用一个名为JSONObject的JSON库(如果需要,我不介意切换)。

我知道如何在JSONArrays上迭代,但是当我解析来自Facebook的JSON数据时,我得到的不是一个数组,而是一个JSONObject,但是我需要能够通过它的索引来访问一个项目,比如JSONObject[0]来获得第一个项目,但是我不知道怎么做。

{
   "http://http://url.com/": {
      "id": "http://http://url.com//"
   },
   "http://url2.co/": {
      "id": "http://url2.com//",
      "shares": 16
   }
   ,
   "http://url3.com/": {
      "id": "http://url3.com//",
      "shares": 16
   }
}
EN

回答 16

Stack Overflow用户

发布于 2012-05-15 11:36:10

也许这会有所帮助:

JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();

while(keys.hasNext()) {
    String key = keys.next();
    if (jsonObject.get(key) instanceof JSONObject) {
          // do something with jsonObject here      
    }
}
票数 659
EN

Stack Overflow用户

发布于 2014-09-22 22:49:58

在我的例子中,我发现迭代names()效果很好。

for(int i = 0; i<jobject.names().length(); i++){
    Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i)));
}
票数 97
EN

Stack Overflow用户

发布于 2015-09-05 19:25:27

我将避免使用迭代器,因为它们可以在迭代期间添加/删除对象,也可以用于循环的干净代码。它将非常简洁&更少的代码行。

使用Java 8和Lamda Update 4/2/2019

import org.json.JSONObject;

public static void printJsonObject(JSONObject jsonObj) {
    jsonObj.keySet().forEach(keyStr ->
    {
        Object keyvalue = jsonObj.get(keyStr);
        System.out.println("key: "+ keyStr + " value: " + keyvalue);

        //for nested objects iteration if required
        //if (keyvalue instanceof JSONObject)
        //    printJsonObject((JSONObject)keyvalue);
    });
}

使用旧方式更新2019年4月2日

import org.json.JSONObject;

public static void printJsonObject(JSONObject jsonObj) {
    for (String keyStr : jsonObj.keySet()) {
        Object keyvalue = jsonObj.get(keyStr);

        //Print key and value
        System.out.println("key: "+ keyStr + " value: " + keyvalue);

        //for nested objects iteration if required
        //if (keyvalue instanceof JSONObject)
        //    printJsonObject((JSONObject)keyvalue);
    }
}

原始答案

import org.json.simple.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
    for (Object key : jsonObj.keySet()) {
        //based on you key types
        String keyStr = (String)key;
        Object keyvalue = jsonObj.get(keyStr);

        //Print key and value
        System.out.println("key: "+ keyStr + " value: " + keyvalue);

        //for nested objects iteration if required
        if (keyvalue instanceof JSONObject)
            printJsonObject((JSONObject)keyvalue);
    }
}
票数 73
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9151619

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档