这段代码应该读取JSON文件这是一个元素数组,然后它应该读取该数组的所有元素,但我得到的结果只有一行,它看起来像这样
reviews[{"sourceId":"890cdd7974cdf8aabe6e9051f5a87303bdb933ae","logoHref":null,"reviewerId":null,"reviewCreatedOnTime":161157...
下面是读取文件的代码:
FileReader read=new FileReader("C:\Users\User\eclipse-workspace\Task\files\reviews.json");
JSONParser parser=new JSONParser();
Object obj=parser.parse(read);
JSONObject jsonObject=new JSONObject();
jsonObject=(JSONObject) obj;
JSONArray reviews = new JSONArray();
reviews=(JSONArray) jsonObject.get("reviews");
Iterator<Map.Entry> itr1 = jsonObject.entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " " + pair.getValue());
}
//json file
{
"reviews":[
{
"id": 2097047,
"reviewId": "93f131be27dc1122bb7ef0048ad10e4f",
"reviewFullText": "5 star review",
"reviewText": "5 star review",
"numLikes": 0,
"numComments": 0,
"numShares": 0,
"rating": 5,
"reviewCreatedOn": "2 months ago",
"reviewCreatedOnDate": "2021-01-25T13:00:35+00:00",
"reviewCreatedOnTime": 1611579635,
"reviewerId": null,
"reviewerUrl": null,
"reviewerName": "Reviewer #20",
"reviewerEmail": null,
"sourceType": "custom",
"isVerified": false,
"source": "custom",
"sourceName": "1-20 Reviews",
"sourceId": "890cdd7974cdf8aabe6e9051f5a87303bdb933ae",
"tags": [],
"href": null,
"logoHref": null,
"photos": []
},
您的第一个问题是您没有采取reviews
对象,而是仍然引用主要的json对象。
Iterator<Map.Entry> itr1 = jsonObject.entrySet().iterator();
应该将jsonObject
更改为reviews
,但同时,鉴于它是JSONArray
的事实,由于您说它只会是数组中的单个元素,您可以从数组中取出第一个元素,即.get(0)
那么你的代码将改变如下:
Iterator<Entry> itr1 = ((JSONObject)reviews.get(0)).entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
System.out.println(pair.getKey() + " " + pair.getValue());
}
你的输出是你所期望的:
sourceId 890cdd7974cdf8aabe6e9051f5a87303bdb933ae
logoHref null
reviewerId null
reviewCreatedOnTime 1611579635
isVerified false
rating 5
reviewerUrl null
reviewFullText 5 star review
source custom
numLikes 0
reviewCreatedOnDate 2021-01-25T13:00:35+00:00
photos []
tags []
numComments 0
reviewerName Reviewer #20
sourceType custom
reviewerEmail null
numShares 0
id 2097047
sourceName 1-20 Reviews
href null
reviewId 93f131be27dc1122bb7ef0048ad10e4f
reviewCreatedOn 2 months ago
reviewText 5 star review
如果您想处理所有评论,并将每个评论作为一个映射来阅读,您可以这样做:
FileReader read = new FileReader(
"C:\Users\User\eclipse-workspace\Task\files\reviews.json");
JSONParser parser = new JSONParser();
Object obj = parser.parse(read);
JSONObject jsonObject = new JSONObject();
jsonObject = (JSONObject) obj;
JSONArray reviews = new JSONArray();
reviews = (JSONArray) jsonObject.get("reviews");
Iterator<Entry> itr1 = reviews.iterator();
while (itr1.hasNext()) {
Iterator<Entry> itr2 = ((JSONObject) itr1.next()).entrySet().iterator();
while (itr2.hasNext()) {
Map.Entry pair = itr2.next();
System.out.println(pair.getKey() + " " + pair.getValue());
}
}
旁注:我建议您使用更简单的方法来构建良好的库,如jackson
或gson
,而不是以这种方式操作数据。