Reputation: 1820
Here's my code:
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String temp = reader.readLine();
if(temp!=null)
result = new JSONObject(temp);
} catch (Exception e) {
e.printStackTrace();
}
As you see, I assign String to String type object, but when code runs, result="true"
and I get exception:
Value true of type java.lang.Boolean cannot be converted to JSONObject
That's frustrating.. should I cast or use .toString()
for a String object? Why it's automatically converted to Boolean?
Update I've figured out, that this is not a Java issue, but JSONObject constructor is not receiving valid JSONObject.
Upvotes: 0
Views: 457
Reputation:
"true"
is not a JSONObject
. A JSONObject
is
an unordered collection of name/value pairs.
quoting from the same source as @devnull. Java is not interpreting the String
result
as a Boolean
, rather the JSON value represented by the String "true"
is correctly interpreted as a JSON boolean. Clearly, it is not a collection of name/value pairs, which is denoted as @Leos Literak suggested using curly braces, colons and semicolons:
{ key : "value"; otherkey : true }
I hope this helps. The term 'object' is used very differently in Java and JSON.
Upvotes: 2
Reputation: 123608
What you're observing is expected. Quoting from JSONObject
:
Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters:
{ } [ ] / \ : , = ; #
and if they do not look like numbers and if they are not the reserved wordstrue
,false
, ornull
.
Upvotes: 2