How to parse JSON boolean value?

Clash Royale CLAN TAG#URR8PPP
How to parse JSON boolean value?
I have a JSON object
JSONObject jsonObject = new JSONObject();
I'm able to populate the object successfully but, when I try to parse a boolean JSON value I get an error:
boolean
08-28 15:06:15.809: E/Buffer Error(31857): Error converting result
java.lang.ClassCastException: java.lang.Integer cannot be cast to
java.lang.Boolean
I do it like this:
boolean multipleContacts = (Boolean) jsonObject.get("MultipleContacts");
My JSON object graph is very simple, the boolean is stored in my database as BIT field (0 or 1)
How do I solve this ?
Here is my JSON:
"ACCOUNT_EXIST": 1,
"MultipleContacts": 0
4 Answers
4
A boolean is not an integer; 1 and 0 are not boolean values in Java. You'll need to convert them explicitly:
1
0
boolean multipleContacts = (1 == jsonObject.getInt("MultipleContacts"));
or serialize the ints as booleans from the start.
A think it would be
0 !=[...]. At least it is in almost all languages.– Lucas Henrique
Jul 13 '15 at 16:31
0 !=
More precisely "Unlike in many C-derived languages, in Java a boolean is not an integer..."
– John Hascall
Dec 9 '16 at 14:55
Try this:
"ACCOUNT_EXIST": true,
"MultipleContacts": false
I cant change my JSON
– meda
Aug 28 '13 at 19:19
You can cast this value to a Boolean in a very simple manner: by comparing it with integer value 1, like this:
boolean multipleContacts = new Integer(1).equals(jsonObject.get("MultipleContacts"))
If it is a String, you could do this:
boolean multipleContacts = "1".equals(jsonObject.get("MultipleContacts"))
Why is either of these better than using
JSONObject#getInt()?– Matt Ball
Aug 28 '13 at 19:19
JSONObject#getInt()
It really isn't - I just gave an answer that could fit a code that wasn't even using JSON.
– Mauren
Aug 28 '13 at 19:45
Try this:
"ACCOUNT_EXIST": true,
"MultipleContacts": false
boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Those are not boolean. JSON Accepts boolean values true and false.
– Pablo Pazos
Jun 28 '17 at 0:08