从字符串中创建列表的名称

时间:2017-01-22 13:31:39

标签: java android json

我有一个json数据,我想在java中对它进行排序。对于每个不存在的类别,我想创建一个新的List。在那之后或者如果类别存在,我想将数据“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 个答案:

答案 0 :(得分:1)

您需要将新的category ArrayList添加到categories并保留对其的引用。你可以使用get()Map的方便方法来打两只果蝇,例如:像这样的东西

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