我想循環一個JSON數組到一個數組列表Category和一個嵌套的Arraylist SubCategory。將對象添加到嵌套for循環內的arraylist
我的問題是,我的列表不僅填充第一個子類數據,而且第二個子類數據。
例如,我想:
1st category [Apple, Kiwi]
2nd category [Mango, Banana]
而是我得到的,
第二類填充爲[Apple,Kiwi,Mango,Banana]
。
ArrayList<Category> categoryName=new ArrayList<Category>();
ArrayList<ArrayList<SubCategory>> subCategoryName = new ArrayList<ArrayList<SubCategory>>();
ArrayList<Integer> subCategoryCount = new ArrayList<Integer>();
ArrayList<SubCategory> subCategoryMatches = new ArrayList<SubCategory>();
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
JSONObject allCategory = (JSONObject) response
.get(i);
int id = allCategory.getInt("mcatid");
String description = allCategory.getString("description");
Category categoryDetails = new Category();
categoryDetails.setCatCode(id);
categoryDetails.setCatName(description);
category_name.add(categoryDetails);
//Log.i(TAG, String.valueOf(description));
JSONArray allSubCategory = allCategory
.getJSONArray("Subcatergory");
for (int j = 0; j < allSubCategory.length(); j++) {
JSONObject jsonObject = allSubCategory.getJSONObject(j);
String subCatId = jsonObject.getString("id");
String subDescription = jsonObject.getString("description");
// retrieve the values like this so on..
//Log.i(TAG, String.valueOf(subDescription));
SubCategory subCategoryMatch = new SubCategory();
subCategoryMatch.setSubCatName(subDescription);
subCategoryMatch.setSubCatCode(subCatId);
subCategoryMatches.add(subCategoryMatch);
}
subcategory_name.add(subCategoryMatches);
subCatCount.add(subCategoryMatches.size());
}
不是我倒下了,但我也不會讀這個。我們很清楚地向你解釋你的問題。你真的需要所有的代碼嗎?也許不是,但無論如何,你應該突出問題所在。 –
你似乎已經有兩個POJO類......爲什麼不使用Gson或Jackson爲你解析這一切? –
[鏈接](https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/) – MehmanBashirov