0

Below is my jsonArray [ { "Average": "107.775", "sum": 431.1, "No of topUps": 4, "MSIDN": "MSISDN2810" }, { "Average": "20.0", "sum": 20, "No of topUps": 1, "MSIDN": "MSISDIN12390" }, { "Average": "22.0", "sum": 88, "No of topUps": 4, "MSIDN": "" }, { "Average": "66.66666666666667", "sum": 200, "No of topUps": 3, "MSIDN": "MS76656" } ]

JSONArray jsonArr = new JSONArray(array.toString()); JSONArray sortedJsonArray = new JSONArray();

    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>() {
        private static final String KEY_NAME = "Average";
        @Override
        public int compare(JSONObject a, JSONObject b) {
            String valA = new String();
            String valB = new String();

            valA = (String) a.get(KEY_NAME);
            valB = (String) b.get(KEY_NAME);

            return valA.compareTo(valB);
        }
    });

    for (int i = 0; i < jsonArr.length(); i++) {
        sortedJsonArray.put(jsonValues.get(i));
    }
SSMD
  • 1
  • 1
  • Does this answer your question? [Sort a Java collection object based on one field in it](https://stackoverflow.com/questions/12542185/sort-a-java-collection-object-based-on-one-field-in-it) – Deckerz Oct 21 '22 at 14:11
  • I do not have a model class , I am inserting jsonobjects by using key value pairs and then adding that json into jsonarray and I need that json array in sorted form based on the average field in decreasing order – SSMD Oct 21 '22 at 17:43

0 Answers0