[Solved] 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

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:

    "MultipleContacts": 0
Enquirer: meda


Solution #1:

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.

Respondent: Matt Ball

Solution #2:

Try this:

    "ACCOUNT_EXIST": true,
    "MultipleContacts": false
Respondent: VM4

Solution #3:

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"))
Respondent: Mauren

Solution #4:

Try this:

    "ACCOUNT_EXIST": true,
    "MultipleContacts": false

boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()
Respondent: jomaac

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy