Reputation: 740
I have a simple json file
{"name":"item1",
"category":"work",
"id":1},
{"name":"item2",
"category":"work",
"id":2},
{"name":"item3",
"category":"work",
"id":3}
{"name":"item4",
"category":"home",
"id":4}
converted to ArrayList i want to group items by category like the following tree view
work -item1 -item2 -item3
home -item4
Any ideas?
private List<Item> item = new ArrayList<Item>();
try {
JSONObject responseObject = new JSONObject(response);
JSONObject itemsObject = responseObject.getJSONObject("items");
Iterator<?> keysIterator = itemsObject.keys();
while(keysIterator.hasNext()) {
String keyString = (String)keysIterator.next();
JSONObject coupon = couponsObject.getJSONObject(keyString);
Item item = new Item();
item.setName(item.getString("name"));
item.setCategory(item.getString("category"));
item.setID(item.getString("id"));
itemList.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
Upvotes: 1
Views: 2387
Reputation:
a little bit logical. try using recursion if the categories and number of objects coming in are dynamic
public void itemSort(String response)
{
map = new HashMap<>();
JSONObject obj = new JSONObject("{\"list\":[" + messageJson + "]}");
JSONArray arrrr = obj.getJSONArray("list");
getItems (arrrr, 0);
System.out.println(map + "");
}
private HashMap<String, String> map;
private void getItems (JSONArray ar, int counter)
{
if (counter < ar.length())
{
JSONObject j = (JSONObject) ar.get(counter);
if (!map.containsKey(j.get("category").toString()))
{
map.put(j.get("category").toString(), j.get("name").toString());
} else
{
map.put(j.get("category").toString(), map.get(j.get("category").toString())
+ "," + j.get("name").toString());
}
counter++;
getItems (ar, counter);
}
}
Upvotes: 0
Reputation: 8640
as @Luiggi suggest, use Map
map will reflect your tree view structure.
all what you need to do is change your code little bit, instead List
define map
Map> items = new HashMap<>();
and other change is in your while loop
where you are creating item
Item item = new Item();
item.setName(item.getString("name"));
item.setCategory(item.getString("category"));
item.setID(item.getString("id"));
List<Item> itemList= items.get(item.getCategotry());
if (itemList ==null){
itemList = new ArrayList<>();
items.put(item.getCategotry(),itemList);
}
itemList.add(item);
Upvotes: 0