JSONArray文本必须以'['at 1 [character 2 line 1]开头

问题描述:

我有一个JSON文件,我正在尝试处理,但出现以下错误:

I have a JSON file and i am trying to deal with but the following error is appears:


线程main中的异常org.json.JSONException:JSONObject文本必须以'{'位于1 [字符2第1行]
开头,位于org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json .JSONObject。(JSONObject.java:195)
at org.json.JSONObject。(JSONObject.java:319)
at amazondataset.AmazonDataset.main(AmazonDataset.java:11)​​
Java结果:1

Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1] at org.json.JSONTokener.syntaxError(JSONTokener.java:433) at org.json.JSONObject.(JSONObject.java:195) at org.json.JSONObject.(JSONObject.java:319) at amazondataset.AmazonDataset.main(AmazonDataset.java:11) Java Result: 1

这是该文件的一个示例:

This is a sample of the file:

{ "reviewerID": "A2SUAM1J3GNN3B", 
  "asin": "0000013714", 
  "reviewerName": "J. McDonald", 
  "helpful": [2, 3], 
  "reviewText": "I bought this for my husband who plays the piano. He is having a wonderful time playing these old hymns. The music is at times hard to read because we think the book was published for singing from more than playing from. Great purchase though!", 
  "overall": 5.0, 
  "summary": "Heavenly Highway Hymns", 
  "unixReviewTime": 1252800000, 
  "reviewTime": "09 13, 2009" 
}

这是我的代码,只是:

JSONObject ar = new JSONObject("E:\\amazonDS.json");

    for (int i = 0; i < ar.length(); i++) {
       System.out.println( "Name: " + ar.getString("reviewerName").toString() );            
    }


你必须阅读内容首先是文件,因为 JSONArray 的构造函数需要该文件-content而不是文件路径。

You have to read the content of the file first, because the constructor of JSONArray needs the file-content and not the file-path.

new JSONObject(new JSONTokener(new FileInputStream(new File("path"), "UTF-8")));

new JSONObject(new JSONTokener(new FileReader("path")));

update
您应该使用文件阅读器或指定字符集对于FileInputStream

update You should use a filereader or specify the charset for the FileInputStream