在查看文档 for JSONObject
时,我注意到了两种方法:getJSONObject(String key)
和optJSONObject(String key)
。从文档中,我认为他们做了几乎相同的事情,但有一个区别:如果找不到键或值,那么getJSONObject()
抛出一个JSONException
,而optJSONObject()
只返回null
。
getJSONObject()
和optJSONObject()
还有其他区别吗?get
相对于opt
的优势是什么,反之亦然?发布于 2021-01-05 21:54:21
getJSONObject()
会抛出异常。optJSONObject()
返回null。当对象不存在时,如果要做更多的工作,则此选项更容易阅读。
JSONObject object = jsonResponse.optJSONObject("object");
if(object == null)
{
// handle not existing here
}
如果只抛出另一个异常或执行其他一行操作,则此选项会更容易一些。
JSONObject object = null;
try
{
object = jsonResponse.getJSONObject("object");
}
catch(JSONException je)
{
// handle object not found here
}
https://stackoverflow.com/questions/11316152
复制相似问题