27

我有一个 JSON 对象

JSONObject jsonObject = new JSONObject();

我能够成功填充对象,但是,当我尝试解析booleanJSON 值时,出现错误:

08-28 15:06:15.809:E/Buffer 错误(31857):转换结果时出错 java.lang.ClassCastException:java.lang.Integer 无法转换为 java.lang.Boolean

我这样做:

boolean multipleContacts = (Boolean) jsonObject.get("MultipleContacts");

我的 JSON 对象图非常简单,布尔值作为 BIT 字段(0 或 1)存储在我的数据库中

我该如何解决这个问题?

这是我的 JSON:

{
    "ACCOUNT_EXIST": 1,
    "MultipleContacts": 0
}
4

4 回答 4

37

Try this:

{
    "ACCOUNT_EXIST": true,
    "MultipleContacts": false
}
于 2013-08-28T19:16:31.300 回答
34

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.

于 2013-08-28T19:16:29.140 回答
1

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"))
于 2013-08-28T19:16:43.073 回答
1

尝试这个:

{
    "ACCOUNT_EXIST": true,
    "MultipleContacts": false
}

boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()
于 2018-08-13T00:49:51.207 回答