Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

java - 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 want to get the Array at the position "result", 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may be passing the STRING to JSONObject with leading spaces. Try trimming

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

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

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

If that still doesn't work, then show what the first character from the string is:

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

You should be expecting 123, the curly braces. In fact, check the entire content

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

You could also try cutting everything before the { in the string

JSONObject allCDs = new JSONObject(objectString.substring(objectString.indexOf('{')));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...