【发布时间】:2012-12-21 12:38:31
【问题描述】:
我有以下方法定义,旨在搜索给定键的 JSON 对象并返回 JSONObject 或该键的字符串值。为了确保它搜索 JSON 对象的每个级别,我将其设为递归,但仅在可以返回更深的 JSONObject 的情况下。编译器抱怨这必须返回一个 Object,因为我已经声明了该返回类型。美好的。在两种情况下,我返回一个对象,但我认为它的问题是在某些情况下它不会返回任何东西。如果我添加最终的返回 false 或其他内容,它将通过编译器检查,但对该方法的调用将始终(最终)返回 false,使其无用。我不习惯像 Java 这样的严格类型的语言,所以我以前没有遇到过类似的问题。任何指针将不胜感激。
public Object find(String contentId, JSONObject node) {
JSONObject currentNode = (node != null) ? node : this.txtContent;
Iterator<?> nodeKeys = currentNode.keys();
while ( nodeKeys.hasNext() ){
try {
String key = (String) nodeKeys.next();
if (key.equals(contentId)) {
if (currentNode.get(key) instanceof JSONObject) {
return currentNode.getJSONObject(key);
} else {
return currentNode.getString(key);
}
} else if (currentNode.get(key) instanceof JSONObject) {
find(contentId, currentNode.getJSONObject(key));
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
【问题讨论】:
-
为什么方法最终总是返回false? (请注意,返回
null通常比在此处返回false更合适......)为什么不对递归调用find返回的值做任何事情? -
它总是返回 false,因为我没有对 find() 的返回值做任何事情,正如你所指出的。
标签: java android json return type-conversion