I have made a jsonarray of jsonobjects. Now I need to sort the JSONArray on base of a value from the jsonobjects. Formerly I sorted ArrayLists of custom objects like this:>
In order to fill up an Android list ArrayAdapter I needed to do just this. This is how I did it:
Activity code building a list from a JSONArray:
JSONArray kids = node.getJSONArray("contents");
kids = JSONUtil.sort(kids, new Comparator(){
public int compare(Object a, Object b){
JSONObject ja = (JSONObject)a;
JSONObject jb = (JSONObject)b;
return ja.optString("name", "").toLowerCase().compareTo(jb.optString("name", "").toLowerCase();
}
});
// in my case I wanted the original larger object contents sorted...
node.put("contents", kids);
And in JSONUtil (my helper):
public static JSONArray sort(JSONArray array, Comparator c){
List asList = new ArrayList(array.length());
for (int i=0; i