loop在java的jsonobject中n次获得相同的对象

brccelvz  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(358)

如何将此响应解析为 ArrayList . 我有一个包含对象列表的层次结构数组,在每个对象中当我得到类型为“group”时就会有 JSONArray 作为“内容”,在 JSONArray 我能得到n个物体。每个对象可以包含“group”类型。如何解析并保存在 ArrayList .

hierarchy: 
[
   {
   "id":"5fd1b4384f5ee9964099b6b0",
   "name":"Dev_5 Category Group `",
   "type":"group",
   "contents":[
      {
         "id":"5fd1b4384f5ee9964099b6af",
         "name":"Dev_5 Parent Category Group 1",
         "type":"group",
         "contents":[
            {
               "id":"5fd1b567505ee9af3a7a65c8",
               "name":"Dev_5 Parent Category Group 2",
               "type":"group",
               "contents":[
                  {
                     "id":"5fd1b4384f5ee9964099b6b1",
                     "type":"category"
                  }
               ],
               "desc":"",
               "image":""
            }
         ],
         "desc":"",
         "image":""
      },
      {
         "id":"5fd1b57b4f5ee9114599b679",
         "type":"category"
      }
   ],
   "desc":"",
   "image":""
  },
{
----
},
{
---
}
]

代码

for (int i = 0; i < hierarchyArray.length(); i++) 
{ 
   hierarchyItemList.clear(); 
   JSONObject obj = hierarchyArray.optJSONObject(i); 
   JSONArray contentArray = obj.optJSONArray("contents"); 
   HierarchyItem item = new HierarchyItem(); 
   item.setId(obj.optString("id")); 
   item.setType(obj.optString("type")); 
   item.setGroupName(obj.optString("name")); 
   if (obj.optString("type").equalsIgnoreCase("group") && contentArray != null && 
   contentArray.length() > 0) { 
         hierarchyItemList.clear(); 
         for (int j = 0; j < contentArray.length(); j++) 
         { 
              hierarchyItemList.add(MenuJSON.hierarchyJSON(contentArray.optJSONObject(j))); 
         } 
   item.setContentList(hierarchyItemList); 
   } 
   if (obj.optString("type").equalsIgnoreCase("category") || 
   (obj.optString("type").equalsIgnoreCase("group") && contentArray != null && 
   contentArray.length() > 0)) { 
      itemList.add(item); 
   }
}

    private static HierarchyItem hierarchyJSON(JSONObject obj) {
        HierarchyItem item = new HierarchyItem();

        item.setId(obj.optString("id"));
        item.setType(obj.optString("type"));
        item.setGroupName(obj.optString("name"));
        JSONArray contentArray = obj.optJSONArray("contents");
        List<HierarchyItem> hierarchyItemList = new ArrayList<>();

        if (obj.optString("type").equalsIgnoreCase("group") && contentArray != null && contentArray.length() > 0) {
            hierarchyItemList.clear();
            for (int j = 0; j < contentArray.length(); j++) {
                hierarchyItemList.add(MenuJSON.hierarchyJSON(contentArray.optJSONObject(j)));
            }
            item.setContentList(hierarchyItemList);
        }

        return item;
    }

使用上述代码,最后一项将更新为中的所有项 ArrayList . 如何解决这个问题。提前谢谢。

g0czyy6m

g0czyy6m1#

您已经清除了每个循环中的值列表,因此现有数据将被清除,并且新值将在列表中更新,因为您使用了递归循环。我删除了list value的clear(),并在循环开始时再次初始化。这会解决你的问题。

for (int i = 0; i < hierarchyArray.length(); i++) 
{

//hierarchyItemList.clear(); --> Remove this clear() method, it will clear your existing values
   JSONObject obj = hierarchyArray.optJSONObject(i); 
   JSONArray contentArray = obj.optJSONArray("contents"); 
   HierarchyItem item = new HierarchyItem(); 
   item.setId(obj.optString("id")); 
   item.setType(obj.optString("type")); 
   item.setGroupName(obj.optString("name")); 
   if (obj.optString("type").equalsIgnoreCase("group") && contentArray != null && 
   contentArray.length() > 0) { 
         //hierarchyItemList.clear(); 
         hierarchyItemList = new ArrayList<>(); // instead of clear the list, initialize it as new list, then it will keep existing list values and load new data in new list
         for (int j = 0; j < contentArray.length(); j++) 
         { 
              hierarchyItemList.add(MenuJSON.hierarchyJSON(contentArray.optJSONObject(j))); 
         } 
   item.setContentList(hierarchyItemList); 
   } 
   if (obj.optString("type").equalsIgnoreCase("category") || 
   (obj.optString("type").equalsIgnoreCase("group") && contentArray != null && 
   contentArray.length() > 0)) { 
      itemList.add(item); 
   }
}

    private static HierarchyItem hierarchyJSON(JSONObject obj) {
        HierarchyItem item = new HierarchyItem();

        item.setId(obj.optString("id"));
        item.setType(obj.optString("type"));
        item.setGroupName(obj.optString("name"));
        JSONArray contentArray = obj.optJSONArray("contents");
        List<HierarchyItem> hierarchyItemList = new ArrayList<>();

        if (obj.optString("type").equalsIgnoreCase("group") && contentArray != null && contentArray.length() > 0) {
            hierarchyItemList.clear();
            for (int j = 0; j < contentArray.length(); j++) {
                hierarchyItemList.add(MenuJSON.hierarchyJSON(contentArray.optJSONObject(j)));
            }
            item.setContentList(hierarchyItemList);
        }

        return item;
    }
pnwntuvh

pnwntuvh2#

如果hierarchyitemlist是您的结果列表,您不应该在多个地方清除它,而应该只在最开始的地方清除它。
这是一个清理过的版本

public class JsonDemo {
  public static void main(String[] args) throws Exception {
    String jsonString = new String(Files.readAllBytes(Paths.get("test.json")), StandardCharsets.UTF_8);
    JSONArray hierarchyJsonArray = new JSONArray(jsonString);
    List<HierarchyItem> hierarchyItemList = new ArrayList<>();
    for(int i = 0; i < hierarchyJsonArray.length(); i++) {
      HierarchyItem hierarchyItem = parseItem(hierarchyJsonArray.getJSONObject(i));
      hierarchyItemList.add(hierarchyItem);
    }
  }

  private static HierarchyItem parseItem(JSONObject jsonObject) {
    HierarchyItem hierarchyItem = new HierarchyItem();
    hierarchyItem.id = jsonObject.optString("id", "");
    hierarchyItem.type = jsonObject.optString("type", "");
    hierarchyItem.name = jsonObject.optString("name", "");
    hierarchyItem.desc = jsonObject.optString("desc", "");
    hierarchyItem.image = jsonObject.optString("image", "");

    // not even checking for type=group, if there is a contents array, parse it
    JSONArray contentsArray = jsonObject.optJSONArray("contents");
    if(contentsArray != null) {
      for(int i = 0; i < contentsArray.length(); i++) {
        // recursive call
        HierarchyItem childItem = parseItem(contentsArray.getJSONObject(i));
        hierarchyItem.contents.add(childItem);
      }
    }

    return hierarchyItem;
  }
}

class HierarchyItem {
  public String              id       = "";
  public String              type     = "";
  public String              name     = "";
  public String              desc     = "";
  public String              image    = "";
  public List<HierarchyItem> contents = new ArrayList<>();
}

test.json:

[
    {
        "id": "5fd1b4384f5ee9964099b6b0",
        "name": "Dev_5 Category Group `",
        "type": "group",
        "contents": [
            {
                "id": "5fd1b4384f5ee9964099b6af",
                "name": "Dev_5 Parent Category Group 1",
                "type": "group",
                "contents": [
                    {
                        "id": "5fd1b567505ee9af3a7a65c8",
                        "name": "Dev_5 Parent Category Group 2",
                        "type": "group",
                        "contents": [
                            {
                                "id": "5fd1b4384f5ee9964099b6b1",
                                "type": "category"
                            }
                        ],
                        "desc": "",
                        "image": ""
                    }
                ],
                "desc": "",
                "image": ""
            },
            {
                "id": "5fd1b57b4f5ee9114599b679",
                "type": "category"
            }
        ],
        "desc": "",
        "image": ""
    },
    {
        "id": "id2",
        "type": "category"
    },
    {
        "id": "id3",
        "type": "category"
    }
]

相关问题