How to sort JSONArray in Android?

/**
     * @param jsonArr = Input your json array
     * @param sortBy  = column name which needs to sort
     * @return required sorted jsonarray
     */
    public static JSONArray sortArray(JSONArray jsonArr, final String sortBy) {
        JSONArray sortedJsonArray = new JSONArray();
        try {
            List<JSONObject> jsonValues = new ArrayList<JSONObject>();
            for (int i = 0; i < jsonArr.length(); i++) {
                jsonValues.add(jsonArr.getJSONObject(i));
            }
            Collections.sort(jsonValues, new Comparator<JSONObject>() {

                @Override
                public int compare(JSONObject a, JSONObject b) {
                    String valA = new String();
                    String valB = new String();

                    try {
                        valA = (String) a.get(sortBy);
                        valB = (String) b.get(sortBy);
                    } catch (JSONException e) {
                        //do something
                    }

                    return valA.compareTo(valB);
                    //if you want to change the sort order, simply use the following:
                    //return -valA.compareTo(valB);
                }
            });

            for (int i = 0; i < jsonArr.length(); i++) {
                sortedJsonArray.put(jsonValues.get(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return sortedJsonArray;
    }

 

Leave a Reply

1 Comment on "How to sort JSONArray in Android?"

avatar
  Subscribe  
newest oldest most voted
Notify of
trackback

[…] This post is moved to http://supportmania.info/how-to-sort-jsonarray-in-android/ […]