这是我的JSON
文件,
[{
"Title": "AY",
"Items": [{
"Name": "Alex",
"RoadNameShort": "AY"
}, {
"Name": "Kep",
"RoadNameShort": "AY"
}, {
"Name": "Lower",
"RoadNameShort": "AY"
}]
}, {
"Title": "BK",
"Items": [{
"Name": "Chantek",
"RoadNameShort": "BK"
}, {
"Name": "Wood",
"RoadNameShort": "BK"
}]
}]
这是我的Java代码,
listDataHeader = new ArrayList<String>();
listDataHeade = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
HashMap<String, String> contact = new HashMap<>();
// Adding child data for lease offer
List<String> lease_offer = new ArrayList<String>();
JSONArray array = new JSONArray(jsonstr);
for (int i = 0; i < array.length(); i++) {
// tmp hash map for single contact
JSONObject c = array.getJSONObject(i);
listDataHeader.add(c.getString("Title"));
String title = c.getString("Title");
JSONArray items = c.getJSONArray("Items");
for (j = 0; j < items.length(); j++) {
JSONObject item = items.getJSONObject(j);
String name = item.getString("Name");
Log.d("email", name);
listDataHeade.add(item.getString("Name"));
lease_offer.add(item.getString("Name"));
// Header into Child data
listDataChild.put(listDataHeader.get(i), lease_offer);
}
}
对于父母,我使用了Title
。孩子是Name
。我正确地获得了标题为AY,BK的组。但我的问题是给孩子的。名称Chantek和木材应属于BK组,而不是AY组。但在AY组,我也让Chantek和木头像孩子一样。
答案 0 :(得分:0)
尝试将listDataChild
移到内部循环之外,因为您需要在迭代所有子项之后将所有子项添加到父列表,并在内部循环开始之前初始化lease_offer
因为每个父项需要创建新的子列表,如下所示:
JSONArray array = new JSONArray(jsonstr);
for (int i = 0; i < array.length(); i++) {
// tmp hash map for single contact
JSONObject c = array.getJSONObject(i);
String title = c.getString("Title");
listDataHeader.add(title);
JSONArray items = c.getJSONArray("Items");
/ Adding child data for lease offer
List<String> lease_offer = new ArrayList<String>();
for (j = 0; j < items.length(); j++) {
JSONObject item = items.getJSONObject(j);
String name = item.getString("Name");
Log.d("email", name);
listDataHeade.add(name);
lease_offer.add(name);
}
// Header into Child data
listDataChild.put(listDataHeader.get(i), lease_offer);
}