Frage

My json looks something like this but a lot more nodes/children:

[{"text":"Millions", "children":[
{"text":"Dinosaur", "children":[{"text":"Stego"}]}, 
{"text":"Dinosaur", "children": [{"text":"T-REX"}]}]}]

I'm trying to recursively go through all the children and add a name/value ("checked": false) pair to the json so that it would now look like:

[{"text":"Millions", "checked": false, "children":[
{"text":"Dinosaur", "checked": false, "children":[{"text":"Stego", "checked": false,}]}, 
{"text":"Dinosaur", "checked": false, "children": [{"text":"T-REX", "checked": false,}]}]}]

What I've come up with so far is:

JSONArray jArrayChecked = new JSONArray();

//This traverses through the nodes
public void addChecked(JSONArray ja){
  for(JSONObject jo : ja){
    if(jo.has("children")
      addChecked(jo.get("children");

    jo.put("checked", false);
    //This part is incorrect
    jArrayChecked.put(jo);
  }
}

How can I properly add the name/value pairs to each node while keeping the node structure intact?

War es hilfreich?

Lösung

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 JSONObjects 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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top