Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào chúng ta có thể sắp xếp một JSONObject trong Java?


A JSONObject là một không có thứ tự bộ sưu tập cặp khóa, giá trị và các giá trị có thể là bất kỳ loại nào trong số này như Boolean, JSONArray, JSONObject, Number Chuỗi . Phương thức khởi tạo của JSONObject có thể được sử dụng để chuyển đổi văn bản JSON ở dạng bên ngoài thành dạng bên trong có các giá trị có thể được truy xuất bằng get () opt () hoặc để chuyển đổi các giá trị thành văn bản JSON bằng cách sử dụng put () toString () các phương pháp.

Trong ví dụ dưới đây, chúng ta có thể sắp xếp các giá trị của JSONObject theo thứ tự giảm dần.

Ví dụ

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;
   }
}

Đầu ra

The values of JSONObject in the descending order:
789
456
123
111