Comment itérer sur un object JSONObject?

J’utilise une bibliothèque JSON appelée JSONObject (cela ne me dérange pas de changer si nécessaire).

Je sais comment itérer sur JSONArrays , mais quand JSONArrays les données JSON de Facebook, je ne reçois pas de tableau, seulement un object JSONObject , mais je dois pouvoir accéder à un élément via son index, comme JSONObject[0] pour obtenir le premier, et je n’arrive pas à comprendre comment le faire.

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

Peut-être que cela aidera:

 jObject = new JSONObject(contents.sortingm()); Iterator keys = jObject.keys(); while( keys.hasNext() ) { Ssortingng key = (Ssortingng)keys.next(); if ( jObject.get(key) instanceof JSONObject ) { } } 

pour mon cas, j’ai trouvé itérer les names() fonctionne bien

 for(int i = 0; i
		      	

Je vais éviter l’iterator car ils peuvent append / supprimer des objects pendant l’itération et aussi pour le code propre utiliser une boucle for. moins de code simple de ligne.

 import org.json.simple.JSONObject; public static void printJsonObject(JSONObject jsonObj) { for (Object key : jsonObj.keySet()) { //based on you key types Ssortingng keyStr = (Ssortingng)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); } } 
 Iterator iterator = jsonObject.values().iterator(); while (iterator.hasNext()) { jsonChildObject = iterator.next(); // Do whatever you want with jsonChildObject Ssortingng id = (Ssortingng) jsonChildObject.get("id"); } 

Ne croyez pas qu’il n’y a pas de solution plus simple et sécurisée que d’utiliser un iterator …

La méthode JSONObject names () retourne un JSONArray des clés JSONObject, vous pouvez donc simplement la parcourir en boucle:

 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 } 

D’abord, mettez ceci quelque part:

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

Ou si vous avez access à Java8, juste ceci:

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

Ensuite, parcourez simplement les clés et les valeurs de l’object:

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

org.json.JSONObject a maintenant une méthode keySet () qui retourne un Set et peut facilement être bouclé avec un for-each.

 for(Ssortingng key : jsonObject.keySet()) 

J’ai créé une petite fonction récursive qui traverse tout l’object json et enregistre le chemin d’access de la clé et sa valeur.

 // My stored keys and values from the json object HashMap myKeyValues = new HashMap(); // Used for constructing the path to the key in the json object Stack key_path = new Stack(); // 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() ){ Ssortingng json_key = (Ssortingng)json_keys.next(); try{ key_path.push(json_key); loadJson(json.getJSONObject(json_key)); }catch (JSONException e){ // Build the path to the key Ssortingng key = ""; for(Ssortingng sub_key: key_path){ key += sub_key+"."; } key = key.subssortingng(0,key.length()-1); System.out.println(key+": "+json.getSsortingng(json_key)); key_path.pop(); myKeyValues.put(key, json.getSsortingng(json_key)); } } if(key_path.size() > 0){ key_path.pop(); } } 

Avec Java 8 et lambda, nettoyez:

 JSONObject jObject = new JSONObject(contents.sortingm()); jObject.keys().forEachRemaining(k -> { }); 

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

Une fois, json avait un json qui avait des identifiants qui devaient être incrémentés de un, car ils étaient indexés à 0 et que cela cassait l’incrémentation automatique de Mysql.

Donc, pour chaque object que j’ai écrit ce code, cela pourrait être utile à quelqu’un:

 public static void incrementValue(JSONObject obj, List keysToIncrementValue) { Set keys = obj.keySet(); for (Ssortingng 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); } } } } } 

usage:

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

cela peut être transformé pour fonctionner avec JSONArray comme object parent aussi

Le code ci-dessous fonctionnait bien pour moi. S’il vous plaît aidez-moi si le réglage peut être fait. Cela récupère toutes les clés même des objects JSON nesteds.

 public static void main(Ssortingng args[]) { Ssortingng s = ""; // Sample JSON to be parsed JSONParser parser = new JSONParser(); JSONObject obj = null; try { obj = (JSONObject) parser.parse(s); @SuppressWarnings("unchecked") List parameterKeys = new ArrayList(obj.keySet()); List result = null; List 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 addNestedKeys(JSONObject obj, List keys, Ssortingng 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 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 nestedKeys = new ArrayList<>(arrayObj.keySet()); for (String s : nestedKeys) { putNestedKeysToList(keys, key, s); addNestedKeys(arrayObj, keys, s); } } return keys; } private static void putNestedKeysToList(List keys, Ssortingng key, Ssortingng 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; }