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会抛出异常。至此,疑惑已经解除。

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...