当前位置: 首页 > 面试题库 >

JSONArray文本必须以'['开头(1 [字符2第1行])

顾文昌
2023-03-14
问题内容

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

线程“主”
org.json.JSONException中的异常:JSONObject文本必须在org.json.JSONObject的org.json.JSONTokener.syntaxError(JSONTokener.java:433)的1
[字符2行1]处以“
{”开头。(JSONObject.java:195)位于org.json.JSONObject。(JSONObject.java:319)位于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() );            
    }

问题答案:

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

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

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

更新 您应该使用FileReader或为FileInputStream指定字符集



 类似资料: