我从 Web 服务调用中获取 JSONObject。
JSONObject result = ...........
当我访问时result.getString("fieldName");
If the fieldName
存在于该 JSONObject 中,那么它工作正常。如果不存在,我会收到异常JSONObject["fieldName"] not found.
我可以用try catch
为此。但是我有近 20 个这样的字段。我是否需要为此使用 20 个 try catch 块,或者是否有其他选择。提前致谢...
有一个方法JSONObject#has(key) https://stleary.github.io/JSON-java/org/json/JSONObject.html#has-java.lang.String-正是为了这个目的。这样就可以避免对每个字段进行异常处理。
if(result.has("fieldName")) {
// It exists, do your stuff
} else {
// It doesn't exist, do nothing
}
此外,您还可以使用JSONObject#isNull(str) https://stleary.github.io/JSON-java/org/json/JSONObject.html#isNull-java.lang.String-方法来检查是否是null
or not.
if(result.isNull("fieldName")) {
// It doesn't exist, do nothing
} else {
// It exists, do your stuff
}
您还可以将逻辑移动到通用方法(为了代码可重用性),您可以在其中传递任何JSONObject
& 如果该字段存在或不存在,则将返回字段名称和方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)