我从webservice调用获取JSONObject.
JSONObject result = ...........
Run Code Online (Sandbox Code Playgroud)
当我访问时 result.getString("fieldName");
如果fieldName存在于那个JSONObject中那么它工作正常.如果不存在我会得到异常JSONObject["fieldName"] not found.
我可以使用这个try catch.但我有近20个这样的字段.我需要使用20个尝试捕获块,或者有任何替代方案.谢谢提前...
Sud*_*hul 39
有一种方法JSONObject#has(key)可用于此目的.这样您就可以避免每个字段的异常处理.
if(result.has("fieldName")){
// It exists, do your stuff
} else {
// It doesn't exist, do nothing
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用该JSONObject#isNull(str)方法来检查它是否是null.
if(result.isNull("fieldName")){
// It doesn't exist, do nothing
} else {
// It exists, do your stuff
}
Run Code Online (Sandbox Code Playgroud)
您还可以将其移动到一个方法(用于代码重用),在该方法中传递JSONObject和String,如果字段存在与否,则返回该方法.
isn*_*bad 12
假设你正在使用org.json.JSONObject,你可以JSONObject#optString(String key, String defaultValue)改用.defaultValue如果key不存在,它将返回:
String value = obj.optString(fieldName, defaultValueIfNull);
Run Code Online (Sandbox Code Playgroud)
更好的解决方案是使用optString而不是getString.
String name = jsonObject.optString("fieldName");
// it will return an empty string ("") if the key you specify doesn't exist
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36815 次 |
| 最近记录: |