Android how to sort JSONArray of JSONObjects

前端 未结 6 1790
一整个雨季
一整个雨季 2020-11-30 09:52

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:

6条回答
  •  悲&欢浪女
    2020-11-30 10:26

    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

提交回复
热议问题