2012-04-03 11 views
39

Mam strumienia json, który może być coś takiego:test jeśli jest JSONObject lub 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" 
         } 
    } 
} 

lub coś

{"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" 
         } 
      }] 
} 

W moim kodu Java I wykonaj następujące czynności:

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

W pierwszym przypadku powyższe nie działa, ponieważ w strumieniu znajduje się tylko jeden element. Jak sprawdzić, czy strumień jest object lub array?

Próbowałem z json.length() ale to nie działa ..

Dzięki

Odpowiedz

89

Coś jak powinien to zrobić:

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 
} 

ma to, że zaletą uzyskania wartości nieruchomości od głównej JSONObject tylko raz. Ponieważ uzyskanie wartości nieruchomości wiąże się z chodzeniem drzewa hash lub podobnego, jest to użyteczne dla wydajności (dla tego, co jest warte).

11

Może sprawdzić jak to?

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

ta zwraca JSONObject lub null, jeśli obiekt interwencja nie jest obiekt JSON. Potem następny to zrobić:

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

To spowoduje powrót tablicę jeśli jego ważność JSONArray albo będzie dać null

+3

** ** Java, nie JavaScript. –

+0

@ T.J.Crowder wow dziękuje, zbyt wcześnie rano, myślę. edytowana odpowiedź –

+0

Dobra edycja, +1 ... –

0

Nie tryied, ale może ...


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); 

Jeśli jest to obiekt JsonArray, wystarczy użyć getAsJsonArray(), aby je rzucić. Jeśli nie, jest to jeden element, więc po prostu go dodaj.

W każdym razie Twój pierwszy przykład jest zepsuty, powinieneś poprosić właściciela serwera, aby to naprawił. Struktura danych JSON musi być spójna. Nie tylko dlatego, że czasami interwencja ma tylko jeden element, który nie musi być tablicą. Jeśli ma tylko jeden element, będzie to tablica składająca się z tylko jednego elementu, ale nadal musi to być tablica, aby klienci mogli je parsować za pomocą zawsze tego samego schematu.

7

Aby było to proste, możesz po prostu sprawdzić pierwszy ciąg z wyniku serwera.

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 
} 

Ta sztuczka opiera się tylko na Ciąg formatu JSON {foo : "bar"} (Object) lub [ {foo : "bar"}, {foo: "bar2"} ] (tablica)

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; 

    } 
Powiązane problemy