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)
A JSONObject is an unordered collection of key and value pairs, resembling Java's native Map implementations. Keys are unique Strings that cannot be null. Values can be anything from a Boolean, Number, String, or JSONArray to even a JSONObject. NULL object.
JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.
java.lang.Object. ↳ org.json.JSONTokener. Parses a JSON (RFC 4627) encoded string into the corresponding object. Most clients of this class will use only need the constructor and nextValue() method.
The JSONPointerException is thrown by JSONPointer if an error occurs during evaluating a pointer. Methods in org.json that return JSONException. Modifier and Type. Method and Description. JSONException.
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('{')));
Found solution! I got this error when i was reading Bulk APi in Java so if you are in the same situation then just add following lines.
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With