JSON เป็นรูปแบบแลกเปลี่ยนข้อมูลยอดนิยมที่ เบาและอิสระจากภาษา JSONArray แปลงข้อความจาก String เป็นอ็อบเจกต์แบบเวกเตอร์ และรองรับอินเตอร์เฟซ java.util.List
ตัวอย่าง: จัดเรียง JSONArray ตามชื่อ
import java.util.*;
import org.json.*;
public class SortJSONArrayTest {
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);
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getJSONObject(i));
}
System.out.println("Before Sorted JSONArray: " + jsonArray);
Collections.sort(list, new Comparator<JSONObject>() {
private static final String KEY_NAME = "Name";
@Override
public int compare(JSONObject a, JSONObject b) {
try {
String str1 = a.getString(KEY_NAME);
String str2 = b.getString(KEY_NAME);
return str1.compareTo(str2);
} catch (JSONException e) {
e.printStackTrace();
return 0;
}
}
});
for (int i = 0; i < list.size(); i++) {
sortedJsonArray.put(list.get(i));
}
System.out.println("Sorted JSON Array with Name: " + sortedJsonArray);
}
}
ผลลัพธ์
Before Sorted JSONArray: [{"ID":"115","Name":"Raja"},{"ID":"120","Name":"Jai"},{"ID":"125","Name":"Adithya"}]
Sorted JSON Array with Name: [{"ID":"125","Name":"Adithya"},{"ID":"120","Name":"Jai"},{"ID":"115","Name":"Raja"}]
แนวทาง: แปลง JSONArray เป็น List → เรียงลำดับด้วย Comparator → สร้าง JSONArray ใหม่