2012-09-25 24 views
18

Buenos días, tengo un conjunto de valores de JSONObject que recibo de un servidor y en los que puedo operar. la mayoría de las veces obtengo un JSONObject con un valor (digamos estadísticas) y, a veces, devuelve un objeto Error con un código y una descripción del error. Ahora mi pregunta es cómo estructurar mi código para que no se rompa si devuelve el error. Pensé que podría hacer esto pero no funciona. Cualquier ayuda será muy apreciada. GraciasCómo probar si un JSONObject es nulo o no existe

public void processResult(JSONObject result) { 

     try { 
      if(result.getJSONObject(ERROR) != null){ 
       JSONObject error = result.getJSONObject(ERROR); 
       String error_detail = error.getString(DESCRIPTION); 
       if(!error_detail.equals(null)){ 

            //show error login here 

       finish(); 
      } 
          else { 

      JSONObject info = result.getJSONObject(STATISTICS); 
      String stats = info.getString("production Stats")); 
      } 
         } 
+0

cuál es el problema ¿En el momento? – waqaslam

Respuesta

8

En JSONObject hay un método 'Has' que puede hacer para Determinar la clave.

No tengo idea de si esto funcionará, pero parece creíble.

public void processResult(JSONObject result) { 

    if(result.has("ERROR")) 
    { 
     JSONObject error = result.getJSONObject("ERROR") 
     String error_detail = error.getString("DESCRIPTION"); 

     if(error_detail != null) 
     { 
      //Show Error Login 
      finish(); 
     } 
    } 
    else if(result.has("STATISTICS")) 
    { 
     JSONObject info = result.getJSONObject("STATISTICS"); 
     String stats = info.getString("Production Stats"); 

     //Do something 
    } 
    else 
    { 
     throw new Exception("Could not parse JSON Object!"); 
    } 
} 
48

Uso .has(String) y .isNull(String)

Un uso conservador podría ser;

if (record.has("my_object_name") && !record.isNull("my_object_name")) { 
     // Do something with object. 
     } 
+2

lo suficientemente gracioso usé el método isNull() solo pero tuve el mismo problema. – irobotxxx

+1

Publique el mensaje JSON que obtiene con la clave ERROR y proporcione el tipo de excepción y ordenaremos esto en un instante. :) – OceanLife

+0

¿Recibió este ordenado @sparrow? – OceanLife

2

Podría ser poco tarde (es seguro) pero publicar para futuros lectores

Puede utilizar JSONObject optJSONObject (String name) que no lanzará ninguna excepción y

Devuelve el valor asignado por nombre si existe y es un JSONObject, o null en caso contrario.

para que pueda hacer

JSONObject obj = null; 
if((obj = result.optJSONObject("ERROR"))!=null){ 
     // it's an error , now you can fetch the error object values from obj 
} 

o si simplemente desea probar la nulidad, sin recuperar ni el valor a continuación

if(result.optJSONObject("ERROR")!=null){ 
    // error object found 
} 

hay familia entera de opt functions que o bien volver null o puede también use la versión sobrecargada para que devuelva cualquier valor predefinido. por ejemplo

String optString (String name, String fallback)

Devuelve el valor asignado por su nombre si existe, coaccionar si necesario, o de reserva si no existe tal correlación.

donde coercing media, intentará convertir el valor en la cadena de tipo


Una versión modificada de la respuesta @TheMonkeyMan para eliminar redundantes look-ups

public void processResult(JSONObject result) { 
    JSONObject obj = null; 
    if((obj = result.optJSONObject("ERROR"))!=null){ 
     //^^^^ either assign null or jsonobject to obj 
     // if not null then found error object , execute if body        
     String error_detail = obj.optString("DESCRIPTION","Something went wrong"); 
     //either show error message from server or default string as "Something went wrong" 
     finish(); // kill the current activity 
    } 
    else if((obj = result.optJSONObject("STATISTICS"))!=null){ 
     String stats = obj.optString("Production Stats"); 
     //Do something 
    } 
    else 
    { 
     throw new Exception("Could not parse JSON Object!"); 
    } 
} 
Cuestiones relacionadas