/** * Recursively look for all key, value pairs and remove keys whose value is "${{@code varName}}". * Is this fragile? To be doubly sure, we do this only for keys with a sibling key "class" that is * a Question class */ private static void recursivelyRemoveOptionalVar(JSONObject questionObject, String varName) throws JSONException { Iterator<?> iter = questionObject.keys(); while (iter.hasNext()) { String key = (String) iter.next(); Object value = questionObject.get(key); if (value instanceof String) { if (value.equals("${" + varName + "}")) { iter.remove(); } } else if (value instanceof JSONObject) { JSONObject childObject = (JSONObject) value; if (childObject.has("class")) { Object classValue = childObject.get("class"); if (classValue instanceof String && isQuestionClass((String) classValue)) { recursivelyRemoveOptionalVar(childObject, varName); } } } } }
recursivelyRemoveOptionalVar(jobj, varName);