微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JSONObject中optString和getString等的区别

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

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

The difference is thatoptStringreturns the empty string ("") if the key you specify doesn't exist.getStringon the other hand throws aJSONException. UsegetStringif it's an error for the data to be missing,oroptStringif you're not sure if it will be there.

简单来说就是optString会在得不到你想要的值时候返回空字符串”“,而getString会抛出异常。至此,疑惑已经解除。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐