PSR PSR - 1 month ago 4x
Java Question

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

I am getting a JSONObject from a webservice call.

JSONObject result = ...........

When i am accessing like

If the
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...


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

    // 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.

    // It doesn't exist, do nothing
} else {
    // It exists, do your stuff

You can also move this to a method(for code re-use), where you pass a JSONObject and a String and the method returns if the field is present or not it.