2015-06-08 4 views
5

ho la seguente stringa passata al server:GSON: non è un oggetto JSON

{ 
    "productId": "", 
    "sellPrice": "", 
    "buyPrice": "", 
    "quantity": "", 
    "bodies": [ 
     { 
      "productId": "1", 
      "sellPrice": "5", 
      "buyPrice": "2", 
      "quantity": "5" 
     }, 
     { 
      "productId": "2", 
      "sellPrice": "3", 
      "buyPrice": "1", 
      "quantity": "1" 
     } 
    ] 
} 

che è un JSON valido per http://jsonlint.com/

voglio ottenere il campo corpi array.

Ecco come lo sto facendo:

Gson gson = new Gson(); 
JsonObject object = gson.toJsonTree(value).getAsJsonObject(); 
JsonArray jsonBodies = object.get("bodies").getAsJsonArray(); 

Ma sulla seconda riga mi sto eccezione elencati di seguito:

HTTP Status 500 - Not a JSON Object: "{\"productId\":\"\",\"sellPrice\":\"\",\"buyPrice\":\"\",\"quantity\":\"\",\"bodies\":[{\"productId\":\"1\",\"sellPrice\":\"5\",\"buyPrice\":\"2\",\"quantity\":\"5\"},{\"productId\":\"2\",\"sellPrice\":\"3\",\"buyPrice\":\"1\",\"quantity\":\"1\"}]}" 

come farlo correttamente allora?

+1

Potrebbe voler dare un'occhiata a questo http://stackoverflow.com/a/15116323/2044733. La seconda opzione, che inizia "Per usare JsonObject", sembra esattamente quello che vuoi. – bbill

risposta

4

Ho utilizzato il metodo parse come descritto in https://stackoverflow.com/a/15116323/2044733 prima e ha funzionato.

Il codice vero e proprio sarebbe simile

JsonParser jsonParser = new JsonParser(); 
jsonParser.parse(json).getAsJsonObject(); 

Da the docs sembra che si sta eseguendo in l'errore descritto in cui il vostro pensa l'oggetto toJsonTree non è del tipo corretto.

Il codice sopra è equivalente a

JsonObject jelem = gson.fromJson(json, JsonElement.class); 

come detto in un'altra risposta qui e sul filo collegato.

+1

sì, la tua soluzione ha funzionato per me! – marknorkin

8

Gson#toJsonTree javadoc afferma

Questo metodo serializza l'oggetto specificato nel suo equivalente rappresentazione come un albero di JsonElement s.

cioè, fondamentalmente fa

String jsonRepresentation = gson.toJson(someString); 
JsonElement object = gson.fromJson(jsonRepresentation, JsonElement.class); 

Un Java String viene convertito in una stringa JSON, vale a dire. a JsonPrimitive, non a JsonObject. In altre parole, toJsonTree sta interpretando il contenuto del valore String passato come stringa JSON, non un oggetto JSON.

Si dovrebbe usare

JsonObject object = gson.fromJson(value, JsonObject.class); 

direttamente, per convertire il vostro String ad un JsonObject.

-1

Che dire di JsonArray jsonBodies = object.getAsJsonArray ("corpi");

+0

Che cosa cambierà considerando l'eccezione che si verifica su 'getAsJsonObject'? –