I don't understand the problem. This works for me
public static void addChecked(JSONArray ja) throws JSONException {
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
if (jo.has("children"))
addChecked((JSONArray) jo.get("children"));
jo.put("checked", false);
}
}
public static void main(String[] args) throws Exception {
String jsonString = "[{\"text\":\"Millions\", \"children\":[{\"text\":\"Dinosaur\", \"children\":[{\"text\":\"Stego\"}]}, {\"text\":\"Dinosaur\", \"children\": [{\"text\":\"T-REX\"}]}]}]";
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println(jsonString);
addChecked(jsonArray);
System.out.println(jsonArray);
}
It prints
[{"text":"Millions", "children":[{"text":"Dinosaur", "children":[{"text":"Stego"}]}, {"text":"Dinosaur", "children": [{"text":"T-REX"}]}]}]
[{"text":"Millions","children":[{"text":"Dinosaur","children":[{"text":"Stego","checked":false}],"checked":false},{"text":"Dinosaur","children":[{"text":"T-REX","checked":false}],"checked":false}],"checked":false}]
You're manipulating the underlying JSONObject
s directly, so no need to reflect the changes in some new JSONArray
.
The solution I've proposed relies heavily on the format of the JSON provided. Keep that in mind if your JSON changes.