JSONObject text must begin with '{'

I have this JSONObject:

{ "gutter_url" : "", "sort_order" : "popularity", "result" : [ { "afs" : "Y", "release_year" : 1979, "album_sort" : "Wall, The" } ] } 

and you want to get the array in the "result" position, so I wrote this code:

 JSONObject allCDs = new JSONObject(objectString); JSONArray CD_List = allCDs.getJSONArray("result"); 

But then I get this exception:

 Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at character 1 at org.json.JSONTokener.syntaxError(JSONTokener.java:410) at org.json.JSONObject.<init>(JSONObject.java:179) at org.json.JSONObject.<init>(JSONObject.java:402) at de.htwberlin.gim.Aufgabe8_5.getCoversFor(Aufgabe8_5.java:55) at de.htwberlin.gim.Aufgabe8_5.main(Aufgabe8_5.java:77) 
+8
java json
source share
2 answers

You can pass STRING to a JSONObject with leading spaces. Try to crop

 JSONObject allCDs = new JSONObject(objectString.replace(/^\s+/,"")); 

EDIT: I thought it was javascript. Try trimming it with Java code instead

 JSONObject allCDs = new JSONObject(objectString.trim()); 

If this still does not work, then show what the first character from the string is:

 System.out.println((int)objectString.trim().charAt(0)); 

You should expect 123, braces. In fact, check all the content

 System.out.println((int)objectString); // or System.out.println((int)objectString.trim()); 

You can also try cutting off everything to {in the line

 JSONObject allCDs = new JSONObject(objectString.substring(objectString.indexOf('{'))); 
+12
source share

You have two commas at the end of this line:

 "sort_order" : "popularity",, 

This should probably be one comma:

 "sort_order" : "popularity", 
+1
source share

Source: https://habr.com/ru/post/651403/


All Articles