A JSONArray text must start with '[' at 1 [character 2 line 1]

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

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

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"  } 

and this is my code, simply:

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

回答1:

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 You should use a filereader or specify the charset for the FileInputStream



回答2:

JSON object look like this:

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

JSON array look like this:

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

W3Schools on JSON

If you output your data - you can valildate it here JSON lint

EDIT:
Whoops, I was a little fast in my answer. Didn't see the java-tag.
This might help - TutorialsPoint - JSON with Java

EDIT Thanks Christian. {} added to the array



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!