2013-02-04 13 views
7

Possible Duplicate:
Determine whether JSON is a JSONObject or JSONArrayCome verificare se la risposta dal server è JSONAobject o JSONArray?

Ho un server che restituisce un po 'di JSONArray di default, ma quando si verifica un errore che mi restituisce JSONObject con codice di errore. Sto cercando di analizzare JSON e controllare gli errori, ho pezzo di codice che verifica l'errore:

public static boolean checkForError(String jsonResponse) { 

    boolean status = false; 
    try { 

     JSONObject json = new JSONObject(jsonResponse); 

     if (json instanceof JSONObject) { 

      if(json.has("code")){ 
       int code = json.optInt("code"); 
       if(code==99){ 
        status = true; 
       } 
      } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return status ; 
} 

ma ottengo JSONException quando jsonResponse è ok ed è un JSONArray (JSONArray non può essere convertito in JsonObject) Come per verificare se jsonResponse mi fornirà JSONArray o JSONObject?

risposta

15

Usa JSONTokener. Lo JSONTokener.nextValue() ti darà un Object che può essere trasmesso dinamicamente al tipo appropriato a seconda dell'istanza.

Object json = new JSONTokener(jsonResponse).nextValue(); 
if(json instanceof JSONObject){ 
    JSONObject jsonObject = (JSONObject)json; 
    //further actions on jsonObjects 
    //... 
}else if (json instanceof JSONArray){ 
    JSONArray jsonArray = (JSONArray)json; 
    //further actions on jsonArray 
    //... 
} 
0

Si sta provando la conversione della stringa di risposta ricevuta dal server in JSONObject che causa l'eccezione. Come hai detto, riceverai il JSONArray dal server, proverai a convertire in JSONArray. Si prega di fare riferimento a questo link che ti aiuterà quando convertire la risposta stringa a JSONObject e JSONArray. Se risposta inizia con [(parentesi quadra aperta Square) quindi convertirlo in JsonArray come di seguito

JSONArray ja = new JSONArray(jsonResponse); 

se la risposta inizia con {(staffa fiore aperto) quindi convertirlo in

JSONObject jo = new JSONObject(jsonResponse); 
Problemi correlati