Uso una biblioteca JSON llamada JSONObject (no me importa cambiar si es necesario).
Sé cómo iterar sobre JSONArrays , pero cuando analizo datos JSON de Facebook no obtengo una matriz, solo un JSONObject , pero necesito poder acceder a un elemento a través de su índice, como JSONObject[0] para obtener el primero, y no sé cómo hacerlo.
{ "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 } }Tal vez esto ayude:
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 } }para mi caso, encontré que iterar los names() funciona bien
for(int i = 0; i<jobject.names().length(); i++){ Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i))); }Evitaré el iterador ya que pueden agregar/eliminar objetos durante la iteración, también para el uso de código limpio para el bucle. será simplemente limpio y con menos líneas.
Uso de Java 8 y Lamda [Actualización 2/4/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); }); }Usando la forma antigua [Actualización 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); } }Respuesta Original
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); } }