2017-08-28 42 views
-1

我想循环一个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()); 
    } 
+1

不是我倒下了,但我也不会读这个。我们很清楚地向你解释你的问题。你真的需要所有的代码吗?也许不是,但无论如何,你应该突出问题所在。 –

+0

你似乎已经有两个POJO类......为什么不使用Gson或Jackson为你解析这一切? –

+0

[链接](https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/) – MehmanBashirov

回答

0

您正在添加到相同的subCategoryMatches列表引用,因此您将获得一个对象中的所有数据。

您需要一个新的清单,然后再添加到循环中。

ArrayList<SubCategory> subCategoryMatches; 

try { 
    // Parsing json array response 
    // loop through each json object 

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

     // New list 
     subCategoryMatches = new ArrayList<SubCategory>(); 

     // Loop and add 
     for (int j = 0; j < allSubCategory.length(); j++) { 
      ... 
      subCategoryMatches.add(subCategoryMatch); 
     } 

     // Add new list to outer list 
     subcategory_name.add(subCategoryMatches); 
    } 
} 
+0

我是一个android初学者plz确切地告诉我在哪里我必须创建该列表以及如何向其添加项目。谢谢 – Naseem

+0

你已经有了这个确切的代码。 '...'是具有完全相同签名的循环后移除的代码。正如我已经写过的那样,新的ArrayList <>'会在之前的行中出现。我不打算复制你的整个代码只是为了显示差异 –

+0

当我把subCategoryMatches =新的ArrayList (); 以上allSubCategory for循环应用程序崩溃当我点击类别 – Naseem