2011-04-06 20 views
22

Tengo algunos problemas al extraer valores de un objeto JSON. Aquí está mi códigoCómo analizar un objeto JSON en Android

try { 
    JSONObject json = new JSONObject(result); 
    JSONObject json2 = json.getJSONObject("results"); 
    test = json2.getString("name");  
} catch (JSONException e) { 
    e.printStackTrace(); 
} 

test se declara como un String. Cuando se ejecuta el código, muestra null. Si desplace el cursor sobre json2 en el modo de depuración, puedo ver todos los valores y nombres dentro del objeto.

También probé

test = json2.length(); 

Este volvió test = 0. Incluso cuando sobrevivo el objeto json2, puedo leer los valores dentro del objeto.

Aquí hay un ejemplo de una cadena JSON que usaré.

{ 
    "caller":"getPoiById", 
    "results": 
    { 
     "indexForPhone":0, 
     "indexForEmail":"NULL", 
     "indexForHomePage":"NULL", 
     "indexForComment":"NULL", 
     "phone":"05137-930 68", 
     "cleanPhone":"0513793068", 
     "internetAccess":"2", 
     "overnightStay":"2", 
     "wasteDisposal":"2", 
     "toilet":"2", 
     "electricity":"2", 
     "cran":"2", 
     "slipway":"2", 
     "camping":"2", 
     "freshWater":"2", 
     "fieldNamesWithValue":["phone"], 
     "fieldNameTranslations": ["Telefon"], 
     "id":"1470", 
     "name":"Marina Rasche Werft GmbH & Co. KG", 
     "latitude":"52.3956107286487", 
     "longitude":"9.56583023071289" 
    } 
} 
+0

Ejemplo de cadena JSON que me proporcionó trabajos al menos. ¿Estás enfrentando problemas con esa cuerda también? – harism

+0

¿Puedes mostrar el código completo para esto? O al menos ayudarme con mi problema con jsonobject – Giant

Respuesta

43

Al final he resuelto mediante el uso de JSONObject.get en lugar de JSONObject.getString y luego arrojados a un testString.

private void saveData(String result) { 
    try { 
     JSONObject json= (JSONObject) new JSONTokener(result).nextValue(); 
     JSONObject json2 = json.getJSONObject("results"); 
     test = (String) json2.get("name"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
} 
+0

Me encontré con el mismo problema y lo resolví siguiendo tu enfoque. ¿Buscó/logró encontrar una explicación de por qué esto funciona pero getJSONObject no? – Raiyan

4
JSONArray jsonArray = new JSONArray(yourJsonString); 

for (int i = 0; i < jsonArray.length(); i++) { 
    JSONObject obj1 = jsonArray.getJSONObject(i); 
    JSONArray results = patient.getJSONArray("results"); 
    String indexForPhone = patientProfile.getJSONObject(0).getString("indexForPhone")); 
} 

Cambiar para JSONArray, a continuación, convertir a JSONObject.

9

En su formato JSON, que no tienen a partir de JSON objeto

igual:

{ 
    "info" :  <!-- this is starting JSON object --> 
     { 
     "caller":"getPoiById", 
     "results": 
     { 
      "indexForPhone":0, 
      "indexForEmail":"NULL", 
      . 
      . 
     } 
    } 
} 

Por encima de JSON comienza con info como objeto JSON. Así, mientras que la ejecución:

JSONObject json = new JSONObject(result); // create JSON obj from string 
JSONObject json2 = json.getJSONObject("info"); // this will return correct 

Ahora, podemos acceder result campo:

JSONObject jsonResult = json2.getJSONObject("results"); 
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG" 

Creo que este había desaparecido y por lo que el problema se resolvió, durante el uso JSONTokener como respuesta de los suyos.

Su respuesta es muy buena. Solo creo que agregue esta información, así que contesté

Gracias

Cuestiones relacionadas