What is the difference between getString()
and optString()
in JSON?
OptString(String)Returns the value mapped by name if it exists, coercing it if necessary, or the empty string if no such mapping exists.
JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With