JSONObjectを反復する方法は?


312

私は呼ばれる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
   }
}


これを試してください:stackoverflow.com/a/56223923/10268067
steve moretz

回答:


594

多分これは役立つでしょう:

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

20
全員に注意してください。jObject.keys()は、逆のインデックス順でイテレータを返します。
macio.Jun 2013

77
@ macio.Junそれにもかかわらず、プロパティのマップでは順序は関係ありません。キーJSONObjectは順序付けされておらず、アサーションはプライベート実装の単純な反映でした;)
caligari

6
すべてのキーを順番に必要とするときに何を使用しますか?
熱心

11
ちょっとした誤解:これはキーの検索を2回行うことにつながりませんか?'Object o = jObject.get(key)'を実行し、その型を確認してから使用すると、get(key)を再度呼び出す必要がなくなります。
トム

1
@Tom ために、各ループコレクションにわたって反復する場合に有用である:for (String key : keys)
カリガリ

86

私の場合、私は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)));
}

1
この例はIteratingJavaのように実際には理解されていませんが、うまく機能します!ありがとう。
TimVisée、2015

57

イテレータは反復中にオブジェクトを追加/削除できるため、ループのクリーンなコードの使用のためにも使用しません。それは単にきれいになり、行が少なくなります。

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

古い方法の使用[Update 4/2/2019]

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

5
彼らはorg.json.simple(これはgoogleライブラリー)を使用しているとは決して言っていません。残念ながら、標準のorg.json.JSONObjectでは、反復子を使用する必要があります。
アマルゴビナス2017年

1
あなたは私を救ったがここに!
ルクルバ2017

1
org.json.JSONObjectにはkeySet()がありません
Ridhuvarshan

どのバージョンを探していますか?stleary.github.io/JSON-java/org/json/JSONObject.html#keySet--
maaz

38

この答えでイテレータを使用するよりも簡単で安全なソリューションがないとは思えません...

JSONObjectのnames ()方法は、返しJSONArrayJSONObjectあなたは、単にループでそれにもかかわらず歩くことができるので、キー:

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

}

1
ここのオブジェクトは何ですか?
RCS

1
ですJSONObject。のようなものJSONObject object = new JSONObject ("{\"key1\",\"value1\"}");。しかし、生のjsonをそれに入れないでput ()くださいobject.put ("key1", "value1");。それにメソッドを使用して項目を追加します。
Acuna

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");
}

jsonChildObject = iterator.next();おそらくjsonChildObject、のようJSONObject jsonChildObject = iterator.next();に定義する必要がありますか?
kontur

1
私はこのソリューションが好きですが、宣言Iterator<JSONObject>すると警告が表示されます。私はそれをジェネリックに置き換え<?>、への呼び出しに対してキャストを行いますnext()。また、キャストを保存するgetString("id")代わりに使用get("id")します。
RTF

9

org.json.JSONObjectにkeySet()メソッドがSet<String>追加されました。これはを返し、for-eachで簡単にループできます。

for(String key : jsonObject.keySet())

これが最も便利な解決策だと思います。アドバイスありがとう:)
Yurii Rabeshko

1
あなたの例を完了することができますか?
キャズム

6

まずこれをどこかに置きます:

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);
    // ...

私はこれに投票しましたが、「String key:....」はコンパイルされず、イテレーターでのチェックされていないキャスト警告を回避する方法がないようです。愚かなイテレータ。
アマルゴビナス2017年

2

jsonオブジェクト全体を通過し、キーパスとその値を保存する小さな再帰関数を作成しました。

// My stored keys and values from the json object
HashMap<String,String> myKeyValues = new HashMap<String,String>();

// Used for constructing the path to the key in the json object
Stack<String> key_path = new Stack<String>();

// Recursive function that goes through a json object and stores 
// its key and values in the hashmap 
private void loadJson(JSONObject json){
    Iterator<?> json_keys = json.keys();

    while( json_keys.hasNext() ){
        String json_key = (String)json_keys.next();

        try{
            key_path.push(json_key);
            loadJson(json.getJSONObject(json_key));
       }catch (JSONException e){
           // Build the path to the key
           String key = "";
           for(String sub_key: key_path){
               key += sub_key+".";
           }
           key = key.substring(0,key.length()-1);

           System.out.println(key+": "+json.getString(json_key));
           key_path.pop();
           myKeyValues.put(key, json.getString(json_key));
        }
    }
    if(key_path.size() > 0){
        key_path.pop();
    }
}

2

Java 8とラムダで、よりクリーン:

JSONObject jObject = new JSONObject(contents.trim());

jObject.keys().forEachRemaining(k ->
{

});

https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#forEachRemaining-java.util.function.Consumer-


キーだけを反復しますが、値を取得する必要があるため、jObject.get(k);を使用できます。
Miquel 2017

「nullからコンシューマへのキャストには最低限のAPI 24が必要です」
Harshil Pansare、2017年

2

以下のコードセットを使用してJSONObjectフィールドを反復処理しました

Iterator iterator = jsonObject.entrySet().iterator();

while (iterator.hasNext())  {
        Entry<String, JsonElement> entry = (Entry<String, JsonElement>) iterator.next();
        processedJsonObject.add(entry.getKey(), entry.getValue());
}

1

私はかつて、それらが0インデックスであり、Mysqlの自動インクリメントを壊していたため、IDを1ずつインクリメントする必要があるjsonを持っていました。

したがって、オブジェクトごとにこのコードを作成しました-誰かに役立つかもしれません:

public static void  incrementValue(JSONObject obj, List<String> keysToIncrementValue) {
        Set<String> keys = obj.keySet();
        for (String key : keys) {
            Object ob = obj.get(key);

            if (keysToIncrementValue.contains(key)) {
                obj.put(key, (Integer)obj.get(key) + 1);
            }

            if (ob instanceof JSONObject) {
                incrementValue((JSONObject) ob, keysToIncrementValue);
            }
            else if (ob instanceof JSONArray) {
                JSONArray arr = (JSONArray) ob;
                for (int i=0; i < arr.length(); i++) {
                    Object arrObj = arr.get(0);
                    if (arrObj instanceof JSONObject) {
                        incrementValue((JSONObject) arrObj, keysToIncrementValue);
                    }
                }
            }
        }
    }

使用法:

JSONObject object = ....
incrementValue(object, Arrays.asList("id", "product_id", "category_id", "customer_id"));

これを変換して、JSONArrayを親オブジェクトとして機能させることもできます。


1

ここでの答えのほとんどは、フラットなJSON構造に関するものです。ネストされたJSONArrayまたはネストされたJSONObjectを持つ可能性があるJSONがある場合、実際の複雑さが生じます。次のコードスニペットは、このようなビジネス要件を処理します。ハッシュマップと、ネストされた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 JSONArray) {
            updateData((JSONObject) keyvalue, mapToUpdate);
        } else {
            // System.out.println("key: " + keyStr + " value: " + keyvalue);
            if (mapToUpdate.containsKey(keyStr)) {
                fullResponse.put(keyStr, mapToUpdate.get(keyStr));
            }
        }
    });

}

ここでは、戻り値の型がvoidであることに注意する必要がありますが、この変更が呼び出し元に反映されるため、siceオブジェクトが渡されます。


0

以下のコードは私にとってはうまくいきました。チューニングができたら助けてください。これにより、ネストされたJSONオブジェクトからでもすべてのキーが取得されます。

public static void main(String args[]) {
    String s = ""; // Sample JSON to be parsed

    JSONParser parser = new JSONParser();
    JSONObject obj = null;
    try {
        obj = (JSONObject) parser.parse(s);
        @SuppressWarnings("unchecked")
        List<String> parameterKeys = new ArrayList<String>(obj.keySet());
        List<String>  result = null;
        List<String> keys = new ArrayList<>();
        for (String str : parameterKeys) {
            keys.add(str);
            result = this.addNestedKeys(obj, keys, str);
        }
        System.out.println(result.toString());
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
public static List<String> addNestedKeys(JSONObject obj, List<String> keys, String key) {
    if (isNestedJsonAnArray(obj.get(key))) {
        JSONArray array = (JSONArray) obj.get(key);
        for (int i = 0; i < array.length(); i++) {
            try {
                JSONObject arrayObj = (JSONObject) array.get(i);
                List<String> list = new ArrayList<>(arrayObj.keySet());
                for (String s : list) {
                    putNestedKeysToList(keys, key, s);
                    addNestedKeys(arrayObj, keys, s);
                }
            } catch (JSONException e) {
                LOG.error("", e);
            }
        }
    } else if (isNestedJsonAnObject(obj.get(key))) {
        JSONObject arrayObj = (JSONObject) obj.get(key);
        List<String> nestedKeys = new ArrayList<>(arrayObj.keySet());
        for (String s : nestedKeys) {
            putNestedKeysToList(keys, key, s);
            addNestedKeys(arrayObj, keys, s);
        }
    }
    return keys;
}

private static void putNestedKeysToList(List<String> keys, String key, String s) {
    if (!keys.contains(key + Constants.JSON_KEY_SPLITTER + s)) {
        keys.add(key + Constants.JSON_KEY_SPLITTER + s);
    }
}



private static boolean isNestedJsonAnObject(Object object) {
    boolean bool = false;
    if (object instanceof JSONObject) {
        bool = true;
    }
    return bool;
}

private static boolean isNestedJsonAnArray(Object object) {
    boolean bool = false;
    if (object instanceof JSONArray) {
        bool = true;
    }
    return bool;
}

-1

これは、問題のもう1つの有効な解決策です。

public void test (){

    Map<String, String> keyValueStore = new HasMap<>();
    Stack<String> keyPath = new Stack();
    JSONObject json = new JSONObject("thisYourJsonObject");
    keyValueStore = getAllXpathAndValueFromJsonObject(json, keyValueStore, keyPath);
    for(Map.Entry<String, String> map : keyValueStore.entrySet()) {
        System.out.println(map.getKey() + ":" + map.getValue());
    }   
}

public Map<String, String> getAllXpathAndValueFromJsonObject(JSONObject json, Map<String, String> keyValueStore, Stack<String> keyPath) {
    Set<String> jsonKeys = json.keySet();
    for (Object keyO : jsonKeys) {
        String key = (String) keyO;
        keyPath.push(key);
        Object object = json.get(key);

        if (object instanceof JSONObject) {
            getAllXpathAndValueFromJsonObject((JSONObject) object, keyValueStore, keyPath);
        }

        if (object instanceof JSONArray) {
            doJsonArray((JSONArray) object, keyPath, keyValueStore, json, key);
        }

        if (object instanceof String || object instanceof Boolean || object.equals(null)) {
            String keyStr = "";

            for (String keySub : keyPath) {
                keyStr += keySub + ".";
            }

            keyStr = keyStr.substring(0, keyStr.length() - 1);

            keyPath.pop();

            keyValueStore.put(keyStr, json.get(key).toString());
        }
    }

    if (keyPath.size() > 0) {
        keyPath.pop();
    }

    return keyValueStore;
}

public void doJsonArray(JSONArray object, Stack<String> keyPath, Map<String, String> keyValueStore, JSONObject json,
        String key) {
    JSONArray arr = (JSONArray) object;
    for (int i = 0; i < arr.length(); i++) {
        keyPath.push(Integer.toString(i));
        Object obj = arr.get(i);
        if (obj instanceof JSONObject) {
            getAllXpathAndValueFromJsonObject((JSONObject) obj, keyValueStore, keyPath);
        }

        if (obj instanceof JSONArray) {
            doJsonArray((JSONArray) obj, keyPath, keyValueStore, json, key);
        }

        if (obj instanceof String || obj instanceof Boolean || obj.equals(null)) {
            String keyStr = "";

            for (String keySub : keyPath) {
                keyStr += keySub + ".";
            }

            keyStr = keyStr.substring(0, keyStr.length() - 1);

            keyPath.pop();

            keyValueStore.put(keyStr , json.get(key).toString());
        }
    }
    if (keyPath.size() > 0) {
        keyPath.pop();
    }
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.