0

I'm sorting json objects in the json array by passing the key name.

Here is the code snippet.

public static void main(String[] args) {
        String jsonArrStr = "[{\r\n" + "    \"id\": 6,\r\n" + " \"name\": \"manu\"\r\n" + "}, {\r\n"
                + " \"id\": 8,\r\n" + " \"name\": \"bharath\"\r\n" + "}, {\r\n" + " \"id\": 5,\r\n"
                + " \"name\": \"magadi\"\r\n" + "}]";

        JSONArray jsonArr = new JSONArray(jsonArrStr);
        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>() {
            // You can change "Name" with "ID" if you want to sort by ID
            private static final String KEY_NAME = "id";

            @Override
            public int compare(JSONObject a, JSONObject b) {
                System.out.println("a " + a.toString());
                System.out.println("b " + b.toString());
                Object valA = new Object();
                Object valB = new Object();

                try {
                    valA = a.get(KEY_NAME);
                    System.out.println("valA " + valA);
                    valB = b.get(KEY_NAME);
                    System.out.println("valB " + valB);
                } catch (JSONException e) {
                    // do something
                }

                return -valA.toString().compareTo(valB.toString());
                // 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));
        }

        System.out.println(sortedJsonArray.toString());

    }
}

this above code works for all the data-types.

Currently I'm able to do sort when we have a pass single key name.

example:- Order by firstName |ASC

But how to handle this for multiple key.

example:- Order by id,firstName | ASC

and it should work like how ORDER BY function is working in db

manu
  • 161
  • 7
  • 4
    Does this answer your question? [How to compare objects by multiple fields](https://stackoverflow.com/questions/369512/how-to-compare-objects-by-multiple-fields) – Milgo Oct 09 '20 at 05:31
  • See especially the [second answer](https://stackoverflow.com/a/25501226/2513200), and note that instead of method references you can also pass lamdas for the field accessors, in your case e.g. `() -> a.get(KEY_NAME)`. It gets a bit more unwieldy if you need to handle exceptions (`JSONException`), though. – Hulk Oct 09 '20 at 05:41

0 Answers0