PSR
PSR

Reputation: 40338

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

Upvotes: 22

Views: 57872

Answers (5)

Rahul
Rahul

Reputation: 45070

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.

Upvotes: 53

isnot2bad
isnot2bad

Reputation: 24454

Assuming that you're using org.json.JSONObject, you can use JSONObject#optString(String key, String defaultValue) instead. It will return defaultValue, if key is absent:

String value = obj.optString(fieldName, defaultValueIfNull);

Upvotes: 16

Mihir Patel
Mihir Patel

Reputation: 486

Way better solution is to use optString instead of getString.

String name = jsonObject.optString("fieldName");
// it will return an empty string ("") if the key you specify doesn't exist

Upvotes: 11

Maelkhor
Maelkhor

Reputation: 61

I use this code to do so, it returns undefined or a specified defaultValue instead of rising exception

/* ex: getProperty(myObj,'aze.xyz',0) // return myObj.aze.xyz safely
 * accepts array for property names: 
 *     getProperty(myObj,['aze','xyz'],{value: null}) 
 */
function getProperty(obj, props, defaultValue) {
    var res, isvoid = function(x){return typeof x === "undefined" || x === null;}
    if(!isvoid(obj)){
        if(isvoid(props)) props = [];
        if(typeof props  === "string") props = props.trim().split(".");
        if(props.constructor === Array){
            res = props.length>1 ? getProperty(obj[props.shift()],props,defaultValue) : obj[props[0]];
        }
    }
    return typeof res === "undefined" ? defaultValue: res;
}

Upvotes: 0

fjtorres
fjtorres

Reputation: 276

Check if your JsonObject implementation contains method called "has". It could be checks if property exist in object.

Many JsonObject implementations contains this method.

Upvotes: 0

Related Questions