如何在 Java 中對 JSONObject 進行排序?
JSONObject 是無序集合,其中包含鍵值對,並且這些值可以是boolean、JSONArray、JSONObject、number和string等任何型別。JSONObject 的建構函式可用於將外部形式的 JSON 文字轉換為內部形式,其值可以用get()和opt() 方法檢索,或使用put()和toString()方法將值轉換為 JSON 文字。
在下面的示例中,我們可以按降序對 JSONObject 的值進行排序。
示例
import org.json.*; import java.util.*; public class JSonObjectSortingTest { public static void main(String[] args) { List<Student> list = new ArrayList<>(); try { JSONObject jsonObj = new JSONObject(); jsonObj.put("Raja", 123); jsonObj.put("Jai", 789); jsonObj.put("Adithya", 456); jsonObj.put("Ravi", 111); Iterator<?> keys = jsonObj.keys(); Student student; while(keys.hasNext()) { String key = (String) keys.next(); student = new Student(key, jsonObj.optInt(key)); list.add(student); } Collections.sort(list, new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { return Integer.compare(s2.pwd, s1.pwd); } }); System.out.println("The values of JSONObject in the descending order:"); for(Student s : list) { System.out.println(s.pwd); } } catch(JSONException e) { e.printStackTrace(); } } } // Student class class Student { String username; int pwd; Student(String username, int pwd) { this.username = username; this.pwd = pwd; } }
輸出
The values of JSONObject in the descending order: 789 456 123 111
廣告