Java 如何解析 JSON 布尔值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18496372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse JSON boolean value?
提问by meda
I have a JSON object
我有一个 JSON 对象
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
JSON 值时出现错误:
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
08-28 15:06:15.809: E/Buffer Error (31857): 错误转换结果 java.lang.ClassCastException: java.lang.Integer 不能转换为 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)
我的 JSON 对象图非常简单,布尔值作为 BIT 字段(0 或 1)存储在我的数据库中
How do I solve this ?
我该如何解决这个问题?
Here is my JSON:
这是我的 JSON:
{
"ACCOUNT_EXIST": 1,
"MultipleContacts": 0
}
采纳答案by Matt Ball
A boolean is not an integer; 1
and 0
are not boolean values in Java. You'll need to convert them explicitly:
布尔值不是整数;1
并且0
不是 Java 中的布尔值。您需要显式转换它们:
boolean multipleContacts = (1 == jsonObject.getInt("MultipleContacts"));
回答by VM4
Try this:
尝试这个:
{
"ACCOUNT_EXIST": true,
"MultipleContacts": false
}
回答by Mauren
You can cast this value to a Boolean in a very simple manner: by comparing it with integer value 1, like this:
您可以以非常简单的方式将此值转换为布尔值:通过将其与整数值 1 进行比较,如下所示:
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"))
回答by jomaac
Try this:
尝试这个:
{
"ACCOUNT_EXIST": true,
"MultipleContacts": false
}
boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()