在JSON对象中存在或不存在检查值以避免JSON异常 [英] check value exist or not in JSON object to avoid JSON exception
问题描述
我从webservice调用中获取JSONObject。
I am getting a JSONObject from a webservice call.
JSONObject result = ...........
我在访问时如 result.getString(fieldName);
如果该JSONObject中存在 fieldName
,那么它工作正常。如果不存在我得到异常找不到JSONObject [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.
我可以使用尝试捕捉
为此。但我有近20个这样的字段。我需要使用20个试试捕获块或者有任何替代方案。谢谢提前...
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...
推荐答案
有一种方法 JSONObject#has(key)
就是为了这个目的。这样就可以避免每个字段的异常处理。
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
}
此外,您可以使用 JSONObject#isNull(str)
方法检查它是否为 null
或不。
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
}
您还可以将其移动到一个方法(用于代码重用),在该方法中传递JSONObject和String,如果字段存在与否,则返回该方法。
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.
这篇关于在JSON对象中存在或不存在检查值以避免JSON异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!