我想循环一个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