使用空字符串按降序排序JSONArray

时间:2015-07-03 12:59:18

标签: android json sorting arraylist hashmap

嗨,请在标记为重复之前查看问题

我有一个jon数组

[
{
"ID":"1324"
"iname":"Abc",
"icounts":"234",
"ilikes":"098"
},
{
"ID":"1224"
"iname":"bcd",
"icounts":"",    //icounts has empty value
"ilikes":"098"
},
{
"ID":"1367"
"iname":"Abc",
"icounts":"28",
"ilikes":"098"
},
{
"ID":"1098"
"iname":"Abc",
"icounts":"",
"ilikes":"098"
},
{
"ID":"1444"
"iname":"dfgbc",
"icounts":"222",
"ilikes":"098"
},
{
"ID":"1411"
"iname":"bwec",
"icounts":"444",
"ilikes":"9"
}

]

我必须按减少顺序“icount”值对其进行排序

ArrayList<HashMap<String,String>> arrayList= ArrayList<HashMap<String,String>>;
String jsonString = EntityUtils.toString(hres.getEntity()); // in jsonString i am storing json response 
JSONArray jarray = new JSONArray(jsonString);
for (int i = 0 ; i <jarray.length();i++)
{
 JSONObject jobj = jarray.getJSONObject(i);
 HashMap<String,String> map = new HashMap<String,String>();
 map.put("ID", jobj.getString("ID"));

 map.put("iname", jobj.getString("iname"));
 map.put("icount", jobj.getString("icount"));
 map.put("ilikes", jobj.getString("ilikes"));
 arrayList.add(map);
 Collections.sort(arrayList, new Comparator<HashMap<String, String>>() {
  @Override
 public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
  return lhs.get("icounts").compareTo(rhs.get("icounts"));
  }
});
}

由于null字段,compareTo未正确排序 所以我想按降序排序。 建议请

1 个答案:

答案 0 :(得分:1)

添加逻辑以检查icount值并添加值&#34; 0&#34;如果是null或空字符串。 例如:

String icounts = jobj.getString("icount");

像这样检查:

if(icounts!=null && icounts.trim().length() >0 )
{
map.put("icount", jobj.getString("icount"));
}
else{
map.put("icount", "0");
}

希望这会对你有所帮助