Check for the existence of fields on JSON
suggest changeSometimes it’s useful to check if a field is present or absent on your JSON to avoid some JSONException
on your code.
To achieve that, use the JSONObject#has(String)
or the method, like on the following 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".
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents