The difference between getString() and optString() in Json

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 11:05:20

As Diego mentions, it's a good idea to check the documentation (this link is now out of date - good thing we have the Wayback Machine!) before posting a question here, but now that you have:

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.

Edit: Full description from the documentation:

Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is not a string and is not null, then it is converted to a string.

Trinadh Koya

If you want to avoid NullPointerException you better make use of optString()

If you are fetching the data from JSON at any time, you might have null data for a particular Key value, at that time instead of implementing Null conditions, better make use of this optimized method optString("<keyname>")

public java.lang.String optString(int index) Get the optional string value associated with an index. It returns an empty string if there is no value at that index. If the value is not a string and is not null, then it is coverted to a string. Parameters: index - The index must be between 0 and length() - 1. Returns: A String value.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!