I have the following method definition which is intended to search a JSON object for a given key and return either the JSONObject or the String value of that key. To ensure it searches through every level of the JSON object I have made it recursive, but only in the event that a deeper JSONObject can be returned. The compiler complains that this must return an Object because I have declared that return type. Fine. In two cases I am returning an object but I think its problem is that in some circumstances it will not return anything. If I add a final return false, or something, it will pass the compiler check but a call to this method will always then (eventually) return false making it useless. I am not used to a strictly typed language like Java so I haven’t encountered a similar issue before. Any pointers would be appreciated.
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);
}
}
}
Let’s see, you should use the value returned by the find call and return null if not found: