check value exist or not in JSON object to avoid JSON exception

java, json

Solution

There is a method `JSONObject#has(key)` meant for exactly this purpose. This way you can avoid the exception handling for each field.

if(result.has("fieldName")) {
    // It exists, do your stuff
} else {
    // It doesn't exist, do nothing 
}

Also, you can use the `JSONObject#isNull(str)` method to check if it is `null` or not.

if(result.isNull("fieldName")) {
    // It doesn't exist, do nothing
} else {
    // It exists, do your stuff
}

You can also move the logic to a common method (for code reusability), where you can pass any `JSONObject` & the field name and the method will return if the field is present or not.

Problem

I am getting a JSONObject from a webservice call. ``` JSONObject result = ........... ``` When i am accessing like `result.getString("fieldName");` If the `fieldName` exist in that JSONObject then it is working fine.If that is not exist i am getting exception `JSONObject["fieldName"] not found.` I can use `try catch` for this.But i have nearly 20 fields like this.Am i need to use 20 try catch blocks for this or is there any alternative for this.Thanks in advance...

Original source