您的位置:首页 > 移动开发 > Objective-C

JSONObject中optString和getString等的区别

2016-08-09 00:00 411 查看
摘要: org.json.JSONObject类中,在同事的提醒下发现还有optString方法,就下来搜集资料查看二者的区别,在这里记录一下,防止遗忘。

同事在看到我写的解析数据代码后,告诉我optString比getString好用,optString不会抛异常,而getString会抛异常,自己是将信将疑,就说,回去后我查查资料。

在在stackoverflow上面看到一个解释如下:

The difference is that
optString
returns the empty string (
""
) if the key you specify doesn't exist.
getString
on the other hand throws a
JSONException
. Use
getString
if it's an error for the data to be missing, or
optString
if you're not sure if it will be there.

简单来说就是optString会在得不到你想要的值时候返回空字符串”“,而getString会抛出异常。至此,疑惑已经解除。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java JSONObject opt
相关文章推荐