Java 检查 JSON 对象中是否存在值以避免 JSON 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20047127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:40:22  来源:igfitidea点击:

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

javajson

提问by PSR

I am getting a JSONObject from a webservice call.

我从网络服务调用中获取 JSONObject。

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

When i am accessing like result.getString("fieldName");

当我访问时 result.getString("fieldName");

If the fieldNameexist in that JSONObject then it is working fine.If that is not exist i am getting exception JSONObject["fieldName"] not found.

如果fieldName存在于该 JSONObject 中,则它工作正常。如果不存在,我将收到异常JSONObject["fieldName"] not found.

I can use try catchfor 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...

我可以用这个try catch。但是我有将近 20 个这样的字段。我需要为此使用 20 个 try catch 块还是有其他选择。提前致谢...

采纳答案by SudoRahul

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

有一种方法JSONObject#has(key)正是为此目的而设计的。这样您就可以避免对每个字段进行异常处理。

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

此外,您可以使用该JSONObject#isNull(str)方法来检查它是否null存在。

if(result.isNull("fieldName")){
    // 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.

您还可以将其移动到一个方法(用于代码重用),在那里您传递一个 JSONObject 和一个字符串,并且该方法返回该字段是否存在。

回答by isnot2bad

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

假设您正在使用org.json.JSONObject,则可以JSONObject#optString(String key, String defaultValue)改为使用。defaultValue如果key不存在,它将返回:

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

回答by fjtorres

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

检查您的 JsonObject 实现是否包含名为“has”的方法。可以检查对象中是否存在属性。

Many JsonObject implementations contains this method.

许多 JsonObject 实现都包含此方法。

回答by Maelkhor

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

回答by Mihir Patel

Way better solution is to use optString instead of getString.

更好的解决方案是使用 optString 而不是 getString。

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