JSONObject obtiene el valor del primer nodo independientemente del nombre

Me pregunto si hay una manera de obtener el valor del primer hijo de un JSONObject sin saber su nombre:

Tengo un JSON entrando con un nodo llamado, this_guy

 {"this_guy": {"some_name_i_wont_know":"the value i care about"}} 

Utilizando JSONObject, ¿cómo puedo obtener "el valor que me importa", limpio si no sé el nombre del niño. Todo lo que sé es "this_guy", alguien?

Utilice JSONObject.keys () que devuelve un iterador de los nombres de String en este objeto . luego utilice estas teclas para recuperar valores.

Para obtener sólo el primer valor:

  Iterator<String> keys = jsonObject.keys(); // get some_name_i_wont_know in str_Name String str_Name=keys.next(); // get the value i care about String value = json.optString(str_Name); 
 Object obj = parser.parse(new FileReader("path2JsonFIle")); JSONObject jsonObject = (JSONObject) obj; 

prueba este iterador

 JSONObject jsonObj = (JSONObject)jsonObject.get("this_guy"); for (Object key : jsonObj.keySet()) { //based on you key types String keyStr = (String)key; Object keyvalue = jsonObj.get(keyStr); /*check here for the appropriate value and do whatever you want*/ //Print key and value System.out.println("key: "+ keyStr + " value: " + keyvalue); } 

una vez que obtiene el valor adecuado, acaba de salir del bucle. por ejemplo, usted dijo que todo lo que necesita es el primer valor en el mapa interior. así que inténtalo como una mujer

 int count = 0; String valuINeed=""; for (Object key : jsonObj.keySet()) { //based on you key types String keyStr = (String)key; Object keyvalue = jsonObj.get(keyStr); valueINeed = (String)keyvalue; count++; /*check here for the appropriate value and do whatever you want*/ //Print key and value System.out.println("key: "+ keyStr + " value: " + keyvalue); if(count==1) break; } System.out.println(valueINeed); 
  • Volley JsonObjectRequest Post parámetros ya no funcionan
  • Fragmento se bloquea con el paquete: no se puede marshal error de valor cuando onPause método se llama
  • Convertir cadena de Android a JSONObject
  • Volley error de excepción cuando el código de respuesta 304 y 200
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.