What is the difference between getString()
and optString()
in JSON?
optString() is used to overcome NullPointerException, which we get while using getString() when the required key doesn't exists in json it basically replaces with the default value.
example let the input Json be
{
"name":"abhi",
"country":"india"
}
now in java when you execute
String city = json.getString("city");
it will throw a NullPointerException
.
by using optString(String key, String default)
we can overcome the above problem.
String city= json.optString("city","default");
System.out.println(city);
Output: default