Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 754
PSR Avatar asked Nov 18 '13 11:11

PSR


People also ask

How do you check if a JSON object exists or not?

jquery json provide several method for getting key value or check if key exists etc. In this example we will use hasOwnProperty method of json object that will help to check if key exists or not in jquery. hasOwnProperty return true if key is exists and return false if key is not exists on given javascript json.

How do you ignore certain values of JSON response?

The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.

How check JSON key exists or not in python?

Check if the key exists or not in JSON if it is present directly to access its value instead of iterating the entire JSON. Note: We used json. loads() method to convert JSON encoded data into a Python dictionary. After turning JSON data into a dictionary, we can check if a key exists or not.


1 Answers

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.

like image 184
Rahul Avatar answered Oct 13 '22 22:10

Rahul