Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is the difference between getString() and optString() in JSON?

like image 647
oferiko Avatar asked Dec 09 '12 19:12

oferiko


People also ask

What is JSON optString?

OptString(String)Returns the value mapped by name if it exists, coercing it if necessary, or the empty string if no such mapping exists.

What is a JsonArray?

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.

What is JSONObject in Java?

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.


1 Answers

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.

like image 180
Jeff Avatar answered Oct 12 '22 19:10

Jeff