22

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

2
  • you can put just ONE try catch around all your stuff. Commented Nov 18, 2013 at 11:55
  • or to check things do if(typeof(JSONObject["fieldName"]) == "undefined")) { //No field set } Commented Nov 18, 2013 at 11:56

5 Answers 5

53

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.

Sign up to request clarification or add additional context in comments.

Comments

16

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);

Comments

11

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

2 Comments

what is type of jsonObject in your case Mihir? pls also mention the dependency version.
It does not give you an empty String. It returns String as "null" (not a null string).
0

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

Many JsonObject implementations contains this method.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.