Sort JSONArray Java: Step-by-Step Guide
To sort a JSONArray, you can follow these steps:
- First, convert the JSONArray to a List object to easily perform sorting operations. You can use the following code to convert JSONArray to List:
JSONArray jsonArray = new JSONArray("[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":30},{\"name\":\"Charlie\",\"age\":20}]");
List<Object> list = jsonArray.toList();
- Next, use the Collections.sort() method to sort the List. You can customize a Comparator to specify the sorting rule. For example, you can sort in ascending order based on the age field.
Collections.sort(list, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
JSONObject obj1 = new JSONObject((Map) o1);
JSONObject obj2 = new JSONObject((Map) o2);
int age1 = obj1.getInt("age");
int age2 = obj2.getInt("age");
return age1 - age2;
}
});
- Finally, convert the sorted List back to a JSONArray. You can use the following code to convert the List to a JSONArray:
JSONArray sortedJsonArray = new JSONArray(list);
System.out.println(sortedJsonArray.toString());
By following the above steps, you can sort the JSONArray.