如何迭代JSONObject?

Eri*_*son 295 java json

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

我知道如何迭代JSONArrays,但是当我从Facebook解析JSON数据时,我没有得到数组,只有a 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
   }
}
Run Code Online (Sandbox Code Playgroud)

小智 569

也许这会有所帮助:

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

  • @ macio.Jun然而,顺序在属性映射中无关紧要:`JSONObject`中的键是无序的,你的断言是私有实现的简单反映;) (76认同)
  • 小心所有人,jObject.keys()返回反向索引顺序的迭代器. (19认同)
  • 轻微的狡辩:这不会导致两次进行密钥查找吗?也许最好做'Object o = jObject.get(key)',然后检查它的类型然后再使用它,而不必再次调用get(key). (11认同)
  • 当我们按顺序需要所有键时要使用什么? (6认同)
  • 我只想提一下,对于那些“keys()”方法没有得到解决的问题的人(说 JSONObject 没有那个方法):你可以输入`jsonObject.keySet().iterator() ` 并且它工作正常。 (2认同)

小智 82

对于我的情况,我发现迭代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)));
}
Run Code Online (Sandbox Code Playgroud)


mta*_*riq 47

我将避免使用迭代器,因为它们可以在迭代期间添加/删除对象,也可以使用for循环来清理代码.少线简单代码.

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

  • 他们从未说过他们使用的是org.json.simple(这是一个谷歌图书馆).遗憾的是,标准的org.json.JSONObject强制您使用迭代器. (5认同)

Acu*_*una 32

无法相信没有比使用迭代器更简单和安全的解决方案......

JSONObject names ()方法返回JSONObject键的JSONArray,因此您可以在循环中简单地遍历它:

JSONObject object = new JSONObject ();
JSONArray keys = object.names ();

for (int i = 0; i < keys.length (); ++i) {

   String key = keys.getString (i); // Here's your key
   String value = object.getString (key); // Here's your value

}
Run Code Online (Sandbox Code Playgroud)

  • 这里的对象是什么? (2认同)

avi*_*sim 18

Iterator<JSONObject> iterator = jsonObject.values().iterator();

while (iterator.hasNext()) {
 jsonChildObject = iterator.next();

 // Do whatever you want with jsonChildObject 

  String id = (String) jsonChildObject.get("id");
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*tok 8

org.json.JSONObject现在有一个keySet()方法,它返回一个Set<String>并且很容易通过for-each循环.

for(String key : jsonObject.keySet())
Run Code Online (Sandbox Code Playgroud)


Ebr*_*owi 6

首先把它放在某个地方:

private <T> Iterable<T> iteratorToIterable(final Iterator<T> iterator) {
    return new Iterable<T>() {
        @Override
        public Iterator<T> iterator() {
            return iterator;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您可以访问Java8,只需:

private <T> Iterable<T> iteratorToIterable(Iterator<T> iterator) {
    return () -> iterator;
}
Run Code Online (Sandbox Code Playgroud)

然后简单地遍历对象的键和值:

for (String key : iteratorToIterable(object.keys())) {
    JSONObject entry = object.getJSONObject(key);
    // ...
Run Code Online (Sandbox Code Playgroud)


She*_*har 6

这里的大多数答案都是针对平面 JSON 结构的,如果您有一个 JSON 可能嵌套了 JSONArrays 或 Nested JSONObjects,那么真正的复杂性就会出现。以下代码片段负责处理此类业务需求。它需要一个哈希映射和带有嵌套 JSONArrays 和 JSONObjects 的分层 JSON,并使用哈希映射中的数据更新 JSON

public void updateData(JSONObject fullResponse, HashMap<String, String> mapToUpdate) {

    fullResponse.keySet().forEach(keyStr -> {
        Object keyvalue = fullResponse.get(keyStr);

        if (keyvalue instanceof JSONArray) {
            updateData(((JSONArray) keyvalue).getJSONObject(0), mapToUpdate);
        } else if (keyvalue instanceof JSONObject) {
            updateData((JSONObject) keyvalue, mapToUpdate);
        } else {
            // System.out.println("key: " + keyStr + " value: " + keyvalue);
            if (mapToUpdate.containsKey(keyStr)) {
                fullResponse.put(keyStr, mapToUpdate.get(keyStr));
            }
        }
    });

}
Run Code Online (Sandbox Code Playgroud)

这里你必须注意,this 的返回类型是 void,但是 sice 对象作为引用传递,这种变化反映给调用者。