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...
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With