Check for the existence of fields on JSON

suggest change

Check whether a field is present before reading it, so a missing key does not throw JSONException.

Use JSONObject.has(String), as in this example:

Sample JSON

{
   "name":"James"
}

Java code

String jsonStr = " { \"name\":\"James\" }";
JSONObject json = new JSONObject(jsonStr);
// Check if the field "name" is present
String name, surname;

// This will be true, since the field "name" is present on our JSON.
if (json.has("name")) {
    name = json.getString("name");
}
else {
    name = "John";
}
// This will be false, since our JSON doesn't have the field "surname".
if (json.has("surname")) {
    surname = json.getString("surname");
}
else {
    surname = "Doe";
}

// Here name == "James" and surname == "Doe".

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents