Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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
}
like image 483
meda Avatar asked Aug 28 '13 19:08

meda


People also ask

Can JSON file have boolean values?

JSON BooleansValues in JSON can be true/false.

How is true boolean value represented in JSON?

In Python, "boolean" is analogous to bool . Note that in JSON, true and false are lower case, whereas in Python they are capitalized ( True and False ).

How do you pass a boolean value in the postman body?

So even if you send a parameter like “active=true”, it is still a string, this is how the HTTP protocol works. Hope this helps clarify the mystery. var bflag = Boolean(“true”); var bflag1 = Boolean(“false”);


3 Answers

Try this:

{
    "ACCOUNT_EXIST": true,
    "MultipleContacts": false
}
like image 101
VM4 Avatar answered Oct 20 '22 05:10

VM4


A boolean is not an integer; 1 and 0 are not boolean values in Java. You'll need to convert them explicitly:

boolean multipleContacts = (1 == jsonObject.getInt("MultipleContacts"));

or serialize the ints as booleans from the start.

like image 35
Matt Ball Avatar answered Oct 20 '22 05:10

Matt Ball


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"))
like image 1
Mauren Avatar answered Oct 20 '22 04:10

Mauren