[英]Error: JSONObject[“result”] is not a JSONObject
I am fetching a JSONObject "result" from the following JSONObject: 我正在从以下JSONObject获取JSONObject“结果”:
{
"success" : true,
"message" : "",
"result" : {
"uuid" : "e606d53c-8d70-11e3-94b5-425861b86ab6"
}
}
I am using this code: 我正在使用此代码:
CloseableHttpClient httpclient = HttpClients.createDefault();
String url = "some url";
HttpGet httpget20 = new HttpGet(url);
httpget20.setHeader("apisign",buildHmacSignature(url, apisecret));
try ( CloseableHttpResponse response2 = httpclient.execute(httpget20)){
HttpEntity entity = response2.getEntity();
JSONObject obj2 = new JSONObject(EntityUtils.toString(entity));
JSONObject result = obj2.getJSONObject("result");
obj2
is the whole json object including "success", "message" and "result". obj2
是整个json对象,包括“成功”,“消息”和“结果”。 However, this line of code generates the following error message: 但是,此代码行生成以下错误消息:
Exception in thread "AWT-EventQueue-0" org.json.JSONException: JSONObject["result"] is not a JSONObject.
I am not sure how a JSONObject can not be a JSONObject. 我不确定JSONObject如何不能是JSONObject。 Can someone explain the problem here?
有人可以在这里解释问题吗?
JSONObject.getJSONObject
can return a JSONObject
only. JSONObject.getJSONObject
只能返回JSONObject
。 It will not return boolean
, long
or String
, and it will not return JSONObject.NULL
in particular, because that is not a JSONObject
itself (it says Java Object
in the docs, and has a specific private type in the implementation). 它不会返回
boolean
, long
或String
,也不会特别返回JSONObject.NULL
,因为它本身不是JSONObject
(它在文档中表示为Java Object
,并且在实现中具有特定的私有类型)。
Use isNull
for checking it beforehand or just accept that it throws an exception and prepare for it. 使用
isNull
事先检查它,或者仅接受它引发异常并为此做准备。 Of course you can also use the generic get
and check the result against JSONObject.NULL
afterwards, perhaps use instanceof
, just none of these will make the code simpler and all of them will introduce casting/casting attempts at some point. 当然,您也可以使用通用的
get
,然后再对JSONObject.NULL
检查结果,也许使用instanceof
,只是这些方法都不会使代码更简单,并且所有方法都会在某些时候引入强制类型转换/广播尝试。
I was linking the Android docs for readability, but you can of course dig into source code too, like getJSONObject
. 我链接了Android文档以提高可读性,但是您当然也可以深入研究源代码,例如
getJSONObject
。 You can find the NULL
at the beginning of the same file if you are interested. 如果您有兴趣,可以在同一文件的开头找到
NULL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.