2012-04-03 15 views
39

Ho un flusso JSON che può essere qualcosa di simile:prova se è JSONObject o JSONArray

{"intervention": 

    { 
     "id":"3", 
       "subject":"dddd", 
       "details":"dddd", 
       "beginDate":"2012-03-08T00:00:00+01:00", 
       "endDate":"2012-03-18T00:00:00+01:00", 
       "campus": 
         { 
         "id":"2", 
         "name":"paris" 
         } 
    } 
} 

o qualcosa di simile

{"intervention": 
      [{ 
       "id":"1", 
       "subject":"android", 
       "details":"test", 
       "beginDate":"2012-03-26T00:00:00+02:00", 
       "endDate":"2012-04-09T00:00:00+02:00", 
       "campus":{ 
         "id":"1", 
         "name":"lille" 
         } 
      }, 

    { 
    "id":"2", 
      "subject":"lozlzozlo", 
      "details":"xxx", 
      "beginDate":"2012-03-14T00:00:00+01:00", 
      "endDate":"2012-03-18T00:00:00+01:00", 
      "campus":{ 
         "id":"1", 
         "name":"lille" 
         } 
      }] 
} 

Nel mio codice Java faccio la seguente:

JSONObject json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream  
JSONArray interventionJsonArray = json.getJSONArray("intervention"); 

Nel primo caso, quanto sopra non funziona perché c'è un solo elemento nello stream .. Come posso verificare se lo stream è un object o ?

ho provato con json.length(), ma non ha funzionato ..

Grazie

risposta

89

Qualcosa del genere dovrebbe farlo:

JSONObject json; 
Object  intervention; 
JSONArray interventionJsonArray; 
JSONObject interventionObject; 

json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream  
Object intervention = json.get("intervention"); 
if (intervention instanceof JSONArray) { 
    // It's an array 
    interventionJsonArray = (JSONArray)intervention; 
} 
else if (intervention instanceof JSONObject) { 
    // It's an object 
    interventionObject = (JSONObject)intervention; 
} 
else { 
    // It's something else, like a string or number 
} 

Questo ha il vantaggio di ottenere il valore della proprietà dal principale JSONObject solo una volta. Dal momento che ottenere il valore della proprietà implica camminare su un albero di hash o simile, è utile per le prestazioni (per quello che vale).

11

Forse un controllo come questo?

JSONObject intervention = json.optJSONObject("intervention"); 

Questo restituisce una JSONObject o nullo se l'oggetto intervento non è un oggetto JSON. Poi prossimo fare questo:

JSONArray interventions; 
if(intervention == null) 
     interventions=jsonObject.optJSONArray("intervention"); 

Questo lo restituisca un array se una valida JSONArray altrimenti darà null

+3

** ** Java, non JavaScript. –

+0

@ T.J.Crowder wow grazie, troppo presto la mattina credo. risposta modificata –

+0

Buona modifica, +1 ... –

0

non l'ho tryied, ma forse ...


JsonObject jRoot = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream 
JsonElement interventionElement = jRoot.get("intervention"); 
JsonArray interventionList = new JsonArray(); 

if(interventionElement.isJsonArray()) interventionList.addAll(interventionElement.getAsJsonArray()); 
else interventionList.add(interventionElement); 

Se si tratta di un oggetto JsonArray, basta usare getAsJsonArray() per lanciarla. In caso contrario, è un singolo elemento, quindi aggiungilo.

In ogni caso, il primo esempio è rotto, è necessario chiedere al proprietario del server di risolverlo. Una struttura dati JSON deve essere coerente. Non è solo perché qualche volta l'intervento viene fornito con solo 1 elemento che non ha bisogno di essere un array. Se ha solo 1 elemento, sarà una matrice di solo 1 elemento, ma deve ancora essere una matrice, in modo che i client possano analizzarla utilizzando sempre lo stesso schema.

7

Per semplificare, è sufficiente controllare la prima stringa dal risultato del server.

String result = EntityUtils.toString(httpResponse.getEntity()); //this function produce JSON 
String firstChar = String.valueOf(result.charAt(0)); 

if (firstChar.equalsIgnoreCase("[")) { 
    //json array 
}else{ 
    //json object 
} 

Questo trucco è basato sulla stringa di formato JSON {foo : "bar"} (oggetto) o [ {foo : "bar"}, {foo: "bar2"} ] (array)

0
//returns boolean as true if it is JSONObject else returns boolean false 
public static boolean returnBooleanBasedOnJsonObject(Object jsonVal){ 
     boolean h = false; 
     try { 
      JSONObject j1=(JSONObject)jsonVal; 
      h=true; 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    if(e.toString().contains("org.json.simple.JSONArray cannot be cast to  org.json.simple.JSONObject")){ 
       h=false; 
      } 
     } 
     return h; 

    } 
Problemi correlati