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.
We'll use the toJson(Object src, Appendable writer) method from the Gson class to convert a Java data type into JSON and store it in a file. The Gson() constructor creates a Gson object with default configuration: Gson gson = new Gson(); Now, we can call toJson() to convert and store Java objects.
InputStream input = new URL("http://exampe.com/get_replies.xml").openStream(); Reader reader = new InputStreamReader(input, "UTF-8"); Gson gs = new Gson(); String s = gs. fromJson(reader, String. class);
Gson (by Google) is a Java library that can be used to convert a Java object into JSON string. Also, it can used to convert the JSON string into equivalent java object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With