Reputation: 766
I have a json data, And I want to sort it in java. For every category that is not existing, I want to create a new List. after that or if the category exists, I want to add the data "desc" "title" "link1" and "link2" to it.
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>>>)
}
Upvotes: 0
Views: 44
Reputation: 37584
You need to add your new category
ArrayList to your categories
and keep a reference on it. You can use the handy method of get()
from the Map
to hit two flies with one stone e.g. something like this
List<List<String>> yourCategoryList = null;
if((yourCategoryList = categories.get(category)) == null){
yourCategoryList = new ArrayList<>();
categories.put(category, yourCategoryList );
}
yourCategoryList.add(product);
Upvotes: 1