繁体   English   中英

递归遍历json,向每个对象添加一个名称/值对

[英]Recursively traverse through json adding a name/value pair to each Object

我的json看起来像这样,但是有更多的节点/子节点:

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

我试图递归地遍历所有子项,并向json添加一个名称/值(“ checked”:false)对,以便现在看起来像:

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

到目前为止,我想出的是:

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);
  }
}

如何在保持节点结构完整的同时,将名称/值对正确添加到每个节点?

我不明白这个问题。 这对我有用

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);
}

它打印

[{"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}]

您直接操作基础JSONObject ,因此无需在某些新JSONArray反映更改。


我提出的解决方案在很大程度上取决于所提供JSON的格式。 如果您的JSON发生变化,请记住这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM