2015-04-30 17 views
24

ho una molto semplice JSON con le recensioni di prodotti, come:come analizzare il file JSON con GSON

{ 
    "reviewerID": "A2XVJBSRI3SWDI", 
    "asin": "0000031887", 
    "reviewerName": "abigail", 
    "helpful": [0, 0], 
    "unixReviewTime": 1383523200, 
    "reviewText": "Perfect red tutu for the price. ", 
    "overall": 5.0, 
    "reviewTime": "11 4, 2013", "summary": "Nice tutu" 
} 
{ 
    "reviewerID": "A2G0LNLN79Q6HR", 
    "asin": "0000031887", 
    "reviewerName": "aj_18 \"Aj_18\"", 
    "helpful": [1, 1], 
    "unixReviewTime": 1337990400, 
    "reviewText": "This was a really cute", 
"overall": 4.0, 
"reviewTime": "05 26, 2012", 
"summary": "Really Cute but rather short." 
} 

mi piacerebbe leggerlo nella mia applicazione Java utilizzando GSON. Ho creato una classe per contenere i risultati per ogni recensione:

public class Review { 
    private String reviewerID; 
    private String asin; 
    private String reviewerName; 
    private ArrayList<Integer> helpful; 
    private String reviewText; 
    private Double overall; 
    private String summary; 
    private Long unixReviewTime; 
    private String reviewTime; 

    public Review() { 
     this.helpful = Lists.newArrayList(); 
    } 
    // some getters and setters... 

di leggere il file JSON, il mio codice è:

Gson gson = new Gson(); 
JsonReader reader = new JsonReader(new FileReader(filename)); 
Review data = gson.fromJson(reader, Review.class); 
data.toScreen(); // prints to screen some values 

Con questo codice, posso recuperare solo la prima recensione in JSON , quindi la mia domanda è: come ripetere tutto il lettore e ottenere le recensioni successive? Non ho bisogno di memorizzare le recensioni in una lista, ho solo bisogno di accedere all'oggetto una volta. Qualsiasi aiuto più che benvenuto.

+0

Analizzare la stringa che si riceve in un nuovo JSONArray(). Per ogni oggetto dell'array, fare gson.fromJson (oggetto, Review.class), quindi aggiungerli tutti a un elenco vuoto list = new LinkedList (); Come in, li analizza tutti in sequenza. – Schaka

risposta

42

È necessario recuperare l'intero dato nell'elenco e quindi eseguire l'iterazione in quanto è un file e altrimenti diventerà inefficiente.

private static final Type REVIEW_TYPE = new TypeToken<List<Review>>() { 
}.getType(); 
Gson gson = new Gson(); 
JsonReader reader = new JsonReader(new FileReader(filename)); 
List<Review> data = gson.fromJson(reader, REVIEW_TYPE); // contains the whole reviews list 
data.toScreen(); // prints to screen some values 
+1

Ho questo errore con il tuo codice: java.lang.IllegalStateException: Expected BEGIN_ARRAY ma era BEGIN_OBJECT alla riga 1 colonna 2 percorso $ – user299791

+1

controlla se il tuo file json è nel formato corretto o no in [jsonlint] (http: // jsonlint. com) –

+1

@Archit Maheshwari - L'input è formattato correttamente ed è valido. Contiene due strutture di dati JSON di tipo "oggetto". È il tuo esempio che non funziona, almeno non con gson 2.8.0. Nondimeno, credo che il tuo esempio fornisca un approccio interessante su come risolvere il problema. Suggerisco di aggiungerlo alla lista dei desideri di Gson. – whaefelinger

17

proprio parsing come un array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class); 

quindi se avete bisogno è anche possibile creare una lista in questo modo:

List<Review> asList = Arrays.asList(reviews); 

P.S. la stringa json dovrebbe essere simile a questa:

[ 
    { 
     "reviewerID": "A2SUAM1J3GNN3B1", 
     "asin": "0000013714", 
     "reviewerName": "J. McDonald", 
     "helpful": [2, 3], 
     "reviewText": "I bought this for my husband who plays the piano.", 
     "overall": 5.0, 
     "summary": "Heavenly Highway Hymns", 
     "unixReviewTime": 1252800000, 
     "reviewTime": "09 13, 2009" 
    }, 
    { 
     "reviewerID": "A2SUAM1J3GNN3B2", 
     "asin": "0000013714", 
     "reviewerName": "J. McDonald", 
     "helpful": [2, 3], 
     "reviewText": "I bought this for my husband who plays the piano.", 
     "overall": 5.0, 
     "summary": "Heavenly Highway Hymns", 
     "unixReviewTime": 1252800000, 
     "reviewTime": "09 13, 2009" 
    }, 

    [...] 
] 
+0

Ho ricevuto un errore con il tuo codice: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: valore atteso alla riga 1 colonna 1 percorso $ – user299791

+1

mostraci le prime righe della tua stringa JSON REALE – dit

+0

scusa il mio il file è 3GB, ho provato a caricare con VIM ma non lo posso caricare – user299791