I have a very simple JSON with reviews for products, like:
{
"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."
}
I'd like to read it into my Java app using GSON. I have built a class to hold results for each review:
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...
To read the JSON file, my code is:
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
With this code, I can only retrieve the first review in the JSON, so my question is: how to iterate through all the reader and get the next reviews? I don't need to store the reviews in a List, just need to access the object once. Any help more than welcome.
You have to fetch the whole data in the list and then do the iteration as it is a file and will become inefficient otherwise.
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