2012-04-24 21 views
12

Voglio deserializzare un array JSON usando Gson. Ho provato a farlo ma non potevo farlo.Come deserializzare un array JSON usando Gson

Il JSON matrice:

[ 
    {"ID":1,"Title":"Lion","Description":"bla bla","ImageURL":"http:\/\/localhost\/lion.jpg"}, 
    {"ID":1,"Title":"Tiger","Description":"bla bla","ImageURL":"http:\/\/localhost\/tiger.jpg"} 
] 

ottengo l'array JSON da uno script PHP:

$array = array (
    array ('ID' => 1 , 'Title' => 'Lion' , 'Description' => 'bla bla' , 'ImageURL' => 'http:\/\/localhost\/lion.jpg') , 
    array ('ID' => 2 , 'Title' => 'Tiger' , 'Description' => 'bla bla' , 'ImageURL' => 'http:\/\/localhost\/tiger.jpg') , 
); 
echo json_encode ($array); 
+0

C'è più senso si può fornire in merito al problema? Qual è l'input, da dove lo ottieni, cosa stai provando? – Michael

+0

Il Proplem è quando cerco di ottenere un array Objcet [] usin gson.fromJson() ottengo un vule null, ottengo questo array JSON da una pagina PHP: –

risposta

36

di deserializzare un JSONArray è necessario utilizzare TypeToken. Puoi leggere ulteriori informazioni a riguardo dal GSON user guide. Esempio di codice:

@Test 
public void JSON() { 
    Gson gson = new Gson(); 
    Type listType = new TypeToken<List<MyObject>>(){}.getType(); 
    // In this test code i just shove the JSON here as string. 
    List<Asd> asd = gson.fromJson("[{'name':\"test1\"}, {'name':\"test2\"}]", listType); 
} 

Se si dispone di un JSONArray quindi è possibile utilizzare

... 
JSONArray jsonArray = ... 
gson.fromJson(jsonArray.toString(), listType); 
... 
+1

cosa è l'elenco asd qui? – Seenu69

+0

Qualcuno può aiutarmi con questo - http://stackoverflow.com/questions/27666558/deserializing-json-array-using-gson? –

+1

FYI, per Type è java.lang.reflect.Type. Esistono milioni di classi di tipi per cui il completamento automatico potrebbe essere fonte di confusione. – Nativ

Problemi correlati