将平面json解析为带有类别的数组

时间:2014-03-31 13:54:00

标签: java android json listview arraylist

我需要动态解析这个扁平的JSON:

    [{"titulo":"prueba1","nombrelinea":"cortecaballero","monto":"12"},
    {"titulo":"prueba1","nombrelinea":"cortedama","monto":"15"},
    {"titulo":"prueba1","nombrelinea":"corteniño","monto":"10"},
    {"titulo":"prueba2","nombrelinea":"tintecaballero","monto":"12"},
    {"titulo":"prueba2","nombrelinea":"tintedama","monto":"15"},
    {"titulo":"prueba2","nombrelinea":"tinteniño","monto":"10"},
    {"titulo":"prueba3","nombrelinea":"secadocaballero","monto":"12"},
    {"titulo":"prueba3","nombrelinea":"secadodama","monto":"15"},
    {"titulo":"prueba3","nombrelinea":"secadoniño","monto":"10"}]

以这种方式进入数组:

 ArrayList<Item> items = new ArrayList<Item>();
     items.add(new SectionItem("prueba 1"));
     items.add(new EntryItem("cortecaballero", "12"));
     items.add(new EntryItem("cortedama", "15"));
     items.add(new EntryItem("corteniño", "12"));
     items.add(new SectionItem("prueba 2"));
     items.add(new EntryItem("tintecaballero", "12"));
     items.add(new EntryItem("tintedama", "15"));
     items.add(new EntryItem("tinteniño", "12"));
     items.add(new SectionItem("prueba 3"));
     items.add(new EntryItem("secadocaballero", "12"));
     items.add(new EntryItem("secadodama", "15"));
     items.add(new EntryItem("secadoniño", "12"));

我已经尝试过,但每次都会重复“titulo”。

1 个答案:

答案 0 :(得分:1)

嗯,最好更改JSON的格式,但如果您没有机会这样做,并且响应结构总是与上面,可能的解决方案是执行以下操作(假设out JSON类型为String的响应:

ArrayList<Item> items = new ArrayList<Item>();
JSONArray jsonArray = new JSONArray(out);
JSONObject jsonObject = new JSONObject();
Set<String> tempSet = new HashSet<String>();
for (int i = 0; i<jsonArray.length();i++){
    jsonObject = jsonArray.getJSONObject(i);
    if (!tempSet.contains(jsonObject.getString("titulo"))){
        items.add(new SectionItem(jsonObject.getString("titulo")));
        tempSet.add(jsonObject.getString("titulo"));
    }
    items.add(new EntryItem(jsonObject.getString("nombrelinea"), jsonObject.getString("monto")));
}

P.S。编辑是为了反映评论中描述的问题