JSONObject的陷阱

public class JO {
	public static void main(String args[]) {
		JSONObject jo = new JSONObject();
		jo.put("isRight", true);
		jo.getBoolean("isRight");
		System.out.print("right");
	}
}

当运行上面的代码的时候,后台会报异常: java

Exception in thread "main" java.lang.ClassCastException: JSONObject["isRight"] is not a Boolean.
	at org.json.JSONObject.getBoolean(JSONObject.java:244)
	at test.basic.kownledge.JO.main(JO.java:9)



The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object



看了api才发现,Jsonobject 不支持boolean类型。

public class JO {
	public static void main(String args[]) {
		JSONObject jo = new JSONObject();
		jo.put("isRight", Boolean.FALSE);
		jo.getBoolean("isRight");
		System.out.print("right");
	}
}
这样写就对了。
相关文章
相关标签/搜索