2017-01-22 10 views
0

私はjsonデータを持っています。そして、それをJavaでソートしたいと思います。既存のカテゴリ以外のカテゴリについては、新しいリストを作成したいと思います。その後、またはカテゴリが存在する場合は、データ "desc" "title" "link1"と "link2"を追加します。文字列のリストの名前を作成します。

 if (jsonStr != null) try { 
      JSONObject jsonObj = new JSONObject(jsonStr); 

      // Getting JSON Array node 
      JSONArray products = jsonObj.getJSONArray("Products"); 

      // looping through All products 
      for (int i = 0; i < products.length(); i++) { 
       JSONObject c = products.getJSONObject(i); 
       String category = c.getString("category"); 
       String title = c.getString("title"); 
       String desc = c.getString("desc"); 
       String link1 = c.getString("link1"); 
       String link2 = c.getString("link2"); 


       // tmp hash map for single contact 
       // HashMap<String, String> contact = new HashMap<>(); 
       List<String> Product = new ArrayList<>(); 

       // adding each child node to HashMap key => value 
       Product.add(category); 
       Product.add(title); 
       Product.add(desc); 
       Product.add(link1); 
       Product.add(link2); 

       if (!categories.contains(category)) { 

        List<List<String>> [category] = new ArrayList<>(); //here I want to create the name of the new list dynamically if it's not existing yet 

       } 
       [category].add(Product); 

       // adding contact to contact list 
       categories.add([category]); // and finally adding the category to the categories list (List<List<List<String>>>) 
      } 

答えて

1

あなたのcategoriesに新しいcategoryのArrayListを追加し、その上に参照を保持する必要があります。 Mapの便利な方法get()を使用して、1つの石で2つのハエを叩くなど、このようなもの

List<List<String>> yourCategoryList = null; 
if((yourCategoryList = categories.get(category)) == null){ 
    yourCategoryList = new ArrayList<>(); 
    categories.put(category, yourCategoryList); 
}  
yourCategoryList.add(product); 
+0

ありがとうございます。 'yourCategory'の名前は' yourCategory'だけです。 json 'Category2'の次の配列に、' Category1'があればこれをどのように変更できますか? –

+0

@EmanuelGrafあなたは変数について話しています。あなたはそれらをあなたが望む名前にすることができます。あなたのカテゴリーは、マップの中にあります。 'categories.get(" Apples ")を使うと、リンゴのための' List'が得られます。 –

+0

@EmanuelGraf私はそれをより良く反映するようにコードを調整しました。このようなカテゴリを追加する 'categories.put(category、yourCategory)' –

関連する問題