2012-08-02 31 views
8

tengo una salida de API como esto:JSONObject en JSONObject

{"user" : {"status" : {"stat1" : "54", "stats2" : "87"}}} 

puedo crear un simple JSONObject de esta API con:

JSONObject json = getJSONfromURL(URL); 

Después de esto puedo leer los datos de usuario de la siguiente manera:

String user = json.getString("user"); 

Pero, ¿cómo puedo obtener los datos para stat1 y stat2?

Respuesta

19

JSONObject proporciona descriptores de acceso para un número de diferentes tipos de datos, incluyendo anidada JSONObjects y JSONArrays, utilizando JSONObject.getJSONObject(String), JSONObject.getJSONArray(String).

dado tu JSON, que había necesidad de hacer algo como esto:

JSONObject json = getJSONfromURL(URL); 
JSONObject user = json.getJSONObject("user"); 
JSONObject status = user.getJSONObject("status"); 
int stat1 = status.getInt("stat1"); 

nota la falta de control de errores aquí: por ejemplo, el código se supone la existencia de los miembros anidados - usted debe comprobar para null - y no hay manejo de excepciones.

+0

¿Querías decir 'JSONObject user = json.getJSONObject (" user ")'? –

+0

@CheJami lo hice, corregido. Gracias – pb2q

1

Para acceder a las propiedades en un JSON puede analizar el objeto con JSON.parse y luego ACCEESS la propiedad requerida como:

var star1 = user.stat1; 
2
JSONObject mJsonObject = new JSONObject(response); 
JSONObject userJObject = mJsonObject.getJSONObject("user"); 
JSONObject statusJObject = userJObject.getJSONObject("status"); 
String stat1 = statusJObject.getInt("stat1"); 
String stats2 = statusJObject.getInt("stats2"); 

de su respuesta usuario y estado es objeto de modo para ese uso getJSONObject y stat1 y stats2 es estado tecla de objeto para ese uso getInt() método para obtener un valor entero y usar getString() método para obtener el valor de cadena.

Cuestiones relacionadas