【发布时间】:2021-03-25 21:07:14
【问题描述】:
如何将此响应解析为ArrayList。我有包含对象列表的层次结构数组,在每个对象中,当我将 type 作为“组”时,JSONArray 将作为“内容”,在 JSONArray 内我可以得到 n 不。的对象。每个对象可能包含类型为“组”。
如何解析并保存在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中的所有项。如何解决这个问题。
提前致谢。
【问题讨论】:
标签: java android json arraylist