如何使用GSON解析JSON文件
我有一个非常简单的JSON,其中包含产品评论,例如:
{
"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."
}
我想使用GSON将其读入我的Java应用程序中。我建立了一个类来保存每次评论的结果:
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...
要读取 JSON 文件,我的代码是:
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
使用此代码,我只能检索JSON中的第一个评论,所以我的问题是:如何迭代所有读者并获得下一个评论?我不需要将评论存储在列表中,只需要访问对象一次。任何帮助都比欢迎。