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