How to check if a JSON key exists? How to check if a JSON key exists? json json

How to check if a JSON key exists?


JSONObject class has a method named "has":

http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

Returns true if this object has a mapping for name. The mapping may be NULL.


You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.

if (json.has("status")) {   String status = json.getString("status"));}if (json.has("club")) {   String club = json.getString("club"));}

You can also check using 'isNull' - Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.

if (!json.isNull("club"))    String club = json.getString("club"));


you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also

use optString instead of getString:

Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists