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

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.

Leave a Comment