Difference between getString () and optString () in Json

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

+65
java json
Dec 09
source share
5 answers

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

The difference is that optString returns an empty string ( "" ) if the key you specified does not exist. getString , on the other hand, throws a JSONException . Use getString if this is an error for data that will be missing, or optString if you are not sure if it will be there.

Edit: Full description from documentation:

Get the optional string associated with the 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.

+117
Dec 09 '12 at 19:14
source share

If you want to avoid a NullPointerException , it is better to use optString()

If you are extracting data from JSON at any time, you may have null data for a specific key value, then instead of fulfilling Null conditions, it is better to use this optimized method optString("<keyname>")

+10
Aug 09 '16 at 8:31
source share

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

+1
Sep 03 '15 at 6:31
source share

1) getString (String name): - This method returns a String value, displayed by name, if it exists, with forced binding, if necessary, or throw JSONException if such a mapping does not exist.

2) optString (String name): - This method returns a String value displayed by name, if it exists, with forced binding if necessary, or an empty string ("") , if no such mapping exists.

0
Sep 09 '19 at 5:33
source share

optString () is used to overcome the NullPointerException that we get when using getString (), when the required key does not exist in json, it is basically replaced with the default value.

For example, let Json input be

 { "name":"abhi", "country":"india" } 

now in java when you execute

 String city = json.getString("city"); 

this will throw a NullPointerException .

with optString(String key, String default) we can overcome the above problem.

 String city= json.optString("city","default"); System.out.println(city); 

Conclusion: default

0
Sep 09 '19 at 6:30
source share



All Articles