[java] JSONObject를 반복하는 방법?

나는 JSON 라이브러리를 사용합니다 JSONObject(필요한 경우 전환하지 않아도됩니다).

반복하는 방법을 알고 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
   }
}



답변

아마도 이것이 도움이 될 것입니다 :

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      
    }
}


답변

내 경우에는 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)));
}


답변

반복하는 동안 객체를 추가 / 제거 할 수 있으며 루프에 대한 코드를 깨끗하게 사용하기 위해 반복자를 피할 수 있습니다. 단순히 깨끗하고 줄이 적습니다.

Java 8 및 Lamda 사용 [업데이트 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);
    }
}


답변

이 답변에 반복자를 사용하는 것보다 더 간단하고 안전한 솔루션이 없다고 믿을 수 없습니다 …

JSONObject names ()메소드는 키 JSONArray중 하나 를 반환 JSONObject하므로 루프를 통해 간단하게 걸을 수 있습니다.

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

}


답변

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

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

 // Do whatever you want with jsonChildObject 

  String id = (String) jsonChildObject.get("id");
}


답변

org.json.JSONObject는 이제 keySet () 메소드를 가지고 있습니다.이 메소드는 a를 리턴 Set<String>하고 for-each로 쉽게 반복 될 수 있습니다.

for(String key : jsonObject.keySet())


답변

먼저 이것을 어딘가에 넣으십시오.

private <T> Iterable<T> iteratorToIterable(final Iterator<T> iterator) {
    return new Iterable<T>() {
        @Override
        public Iterator<T> iterator() {
            return iterator;
        }
    };
}

또는 Java8에 액세스 할 수 있다면 다음과 같습니다.

private <T> Iterable<T> iteratorToIterable(Iterator<T> iterator) {
    return () -> iterator;
}

그런 다음 간단히 객체의 키와 값을 반복하십시오.

for (String key : iteratorToIterable(object.keys())) {
    JSONObject entry = object.getJSONObject(key);
    // ...