2012-03-22 15 views
11

Ricevo una stringa JSON dal sito Web. Ho dati che assomiglia a questo (JSON Array)Come verificare se l'oggetto dato è oggetto o Array nella stringa JSON

myconf= {URL:[blah,blah]} 

ma alcune volte questi dati possono essere (oggetto JSON)

myconf= {URL:{try}} 

anche esso può essere vuoto

myconf= {}  

voglio fare diverse operazioni quando il suo oggetto e diverso quando è un array. Fino ad ora nel mio codice stavo cercando di considerare solo gli array, quindi sto seguendo l'eccezione. Ma non sono in grado di verificare la presenza di oggetti o matrici.

sto ottenendo seguente eccezione

org.json.JSONException: JSONObject["URL"] is not a JSONArray. 

Qualcuno può suggerire come può essere risolto. Qui so che oggetti e matrici sono le istanze dell'oggetto JSON. Ma non sono riuscito a trovare una funzione con cui posso verificare se l'istanza data è una matrice o un oggetto.

Ho provato con questo se condizione, ma senza successo

if (myconf.length() == 0 ||myconf.has("URL")!=true||myconf.getJSONArray("URL").length()==0) 

risposta

23

oggetti JSON e array sono istanze rispettivamente JSONObject e JSONArray,. A questo si aggiunge il fatto che lo JSONObject ha un metodo get che ti restituirà un oggetto che puoi controllare tu stesso senza preoccuparti di ClassCastExceptions, e ci sei.

if (!json.isNull("URL")) 
{ 
    // Note, not `getJSONArray` or any of that. 
    // This will give us whatever's at "URL", regardless of its type. 
    Object item = json.get("URL"); 

    // `instanceof` tells us whether the object can be cast to a specific type 
    if (item instanceof JSONArray) 
    { 
     // it's an array 
     JSONArray urlArray = (JSONArray) item; 
     // do all kinds of JSONArray'ish things with urlArray 
    } 
    else 
    { 
     // if you know it's either an array or an object, then it's an object 
     JSONObject urlObject = (JSONObject) item; 
     // do objecty stuff with urlObject 
    } 
} 
else 
{ 
    // URL is null/undefined 
    // oh noes 
} 
+0

Grazie. Ho modificato la mia domanda potrebbe essere che avrà più senso di quello che mi sto chiedendo. Puoi dare un esempio per if (item instanceof JSONArray). Cosa dovrei inserire se condizione? – Judy

+0

Questo * è * l'esempio. L'operatore 'instanceof' ti dirà se' item' è un 'JSONArray'. Aspetta, lasciami un po 'di carne. – cHao

+0

Grazie Chao. In realtà ha funzionato. Ma anche la stringa può essere vuota. Quindi sto ottenendo errori anche per questo. if (! myconf.isNull ("URL") || (myconf.getJSONArray ("URL")! = null) || myconf.getJSONArray ("URL"). length()> 0) {Oggetto oggetto = myconf.get ("URL"); // altro codice} Ricevo l'eccezione JSONObject ["URL"] non trovato. – Judy

5

Un bel paio di modi.

Questo è meno consigliato se si è interessati a problemi di risorse di sistema/uso improprio dell'uso di eccezioni Java per determinare un array o un oggetto.

try{ 
// codes to get JSON object 
} catch (JSONException e){ 
// codes to get JSON array 
} 

O

Questo è raccomandato.

if (json instanceof Array) { 
    // get JSON array 
} else { 
    // get JSON object 
} 
+0

Grazie, so come rimuovere le eccezioni. Sono preoccupato di controllare il contenuto dell'oggetto e controllare se l'URL è una matrice o un oggetto. – Judy

+0

Sì, se si verifica un'eccezione durante il tentativo di ottenere un oggetto quando si tratta di un array JSON, fornire l'implementazione per ottenere un array nella clausola catch. Questo è un modo, sebbene non raccomandato. –

+0

In realtà sto cercando una funzione che può essere utilizzata in condizione per il controllo. – Judy

0

Utilizzo di risposta @Chao posso risolvere il mio problema. In alternativa, possiamo verificarlo.

Questa è la mia risposta JSON

{ 
    "message": "Club Details.", 
    "data": { 
    "main": [ 
     { 
     "id": "47", 
     "name": "Pizza", 

     } 
    ], 

    "description": "description not found", 
    "open_timings": "timings not found", 
    "services": [ 
     { 
     "id": "1", 
     "name": "Free Parking", 
     "icon": "http:\/\/hoppyclub.com\/uploads\/services\/ic_free_parking.png" 
     } 
    ] 
    } 
} 

Ora è possibile controllare in questo modo ciò che è oggetto JSONObject o JSONArray in risposta.

String response = "above is my reponse"; 

    if (response != null && constant.isJSONValid(response)) 
    { 
     JSONObject jsonObject = new JSONObject(response); 

     JSONObject dataJson = jsonObject.getJSONObject("data"); 

     Object description = dataJson.get("description"); 

     if (description instanceof String) 
     { 
      Log.e(TAG, "Description is JSONObject..........."); 
     } 
     else 
     { 
      Log.e(TAG, "Description is JSONArray..........."); 
     } 
    } 

Questo è usato per il controllo che ha ricevuto JSON è valido o meno

public boolean isJSONValid(String test) { 
     try { 
      new JSONObject(test); 
     } catch (JSONException ex) { 
      // e.g. in case JSONArray is valid as well... 
      try { 
       new JSONArray(test); 
      } catch (JSONException ex1) { 
       return false; 
      } 
     } 
     return true; 
    } 
Problemi correlati