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

时间:2016-10-11 14:27:19

标签: java json

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

  

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

这是文件的示例:

{ "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() );            
    }

3 个答案:

答案 0 :(得分:6)

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

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

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

更新 您应该使用文件阅读器或为FileInputStream指定字符集

答案 1 :(得分:0)

JSON对象如下所示:

{ 'key1':'value1', 'key2':'value2' }

JSON数组如下所示:

{
    "employees":[
        {"firstName":"John", "lastName":"Doe"},
        {"firstName":"Anna", "lastName":"Smith"},
        {"firstName":"Peter", "lastName":"Jones"}
    ]
}

W3Schools on JSON

如果输出数据 - 您可以在此处JSON lint

进行保护

编辑:
哎呀,我的回答有点快。没看到java-tag。
这可能会有所帮助 - TutorialsPoint - JSON with Java

修改 谢谢Christian。 {}添加到数组

答案 2 :(得分:-1)

答案是:

而不是 JSONArray jsonarray1 =新的JSONArray(res.toString());

这样写

JSONArray jsonarray1 =新的JSONArray(res.asString());