How can we sort a JSONObject in Java?

JavaJSONObject Oriented ProgrammingProgramming

A JSONObject is an unordered collection of a key, value pairs, and the values can be any of these types like Boolean, JSONArray, JSONObject, Number and String. The constructor of a JSONObject can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get() and opt() methods or to convert values into a JSON text using the put() and toString() methods.

In the below example, we can sort the values of a JSONObject in the descending order.

Example

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

Output

The values of JSONObject in the descending order:
789
456
123
111
raja
Published on 18-Oct-2019 10:38:54
Advertisements