我有一个简单的json文件
{"name":"item1",
"category":"work",
"id":1},
{"name":"item2",
"category":"work",
"id":2},
{"name":"item3",
"category":"work",
"id":3}
{"name":"item4",
"category":"home",
"id":4}
转换为ArrayList我想按类别对项目进行分组,如下面的树视图
工作 -item1 -item2 -item3
家 -item4
有什么想法吗?
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();
答案 0 :(得分:0)
如@Luiggi建议的那样,使用Map
地图将反映您的树状视图结构。
您需要做的就是稍微改变您的代码,而不是List
定义地图
地图&GT; items = new HashMap&lt;&gt;();
和其他更改位于您创建项目的while loop
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);
答案 1 :(得分:0)
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);
}
}