Vấn đề
JSONArray trong org.json không có phương thức sắp xếp built-in. Cách phổ biến: chuyển sang List<JSONObject>, sắp xếp bằng Collections.sort() với Comparator, rồi xây dựng lại JSONArray.
Ví dụ: Sắp xếp theo field "Name"
import java.util.*;
import org.json.*;
public class SortJsonArrayExample {
public static void main(String[] args) {
String jsonStr = "[{\"ID\":\"115\",\"Name\":\"Raja\"},{\"ID\":\"120\",\"Name\":\"Jai\"},{\"ID\":\"125\",\"Name\":\"Adithya\"}]";
JSONArray jsonArray = new JSONArray(jsonStr);
List<JSONObject> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getJSONObject(i));
}
System.out.println("Trước sắp xếp: " + jsonArray);
Collections.sort(list, new Comparator<JSONObject>() {
private static final String KEY = "Name";
@Override
public int compare(JSONObject a, JSONObject b) {
try {
String v1 = a.getString(KEY);
String v2 = b.getString(KEY);
return v1.compareTo(v2);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
});
JSONArray sortedArray = new JSONArray();
for (JSONObject obj : list) {
sortedArray.put(obj);
}
System.out.println("Sau sắp xếp theo Name: " + sortedArray);
}
}
Kết quả
Trước sắp xếp: [{"ID":"115","Name":"Raja"},{"ID":"120","Name":"Jai"},{"ID":"125","Name":"Adithya"}]
Sau sắp xếp theo Name: [{"ID":"125","Name":"Adithya"},{"ID":"120","Name":"Jai"},{"ID":"115","Name":"Raja"}]
Lưu ý: Từ Java 8, có thể dùng lambda: list.sort(Comparator.comparing(o -> o.optString("Name")));. Cần xử lý JSONException khi get giá trị.