How can we sort a JSONObject in Java?

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 {
         <strong>JSONObject </strong>jsonObj = new <strong>JSONObject</strong><strong>()</strong>;
         jsonObj.<strong>put</strong>("Raja", 123);
         jsonObj.<strong>put</strong>("Jai", 789);
         jsonObj.<strong>put</strong>("Adithya", 456);
         jsonObj.<strong>put</strong>("Ravi", 111);
         Iterator<?><!--?--> keys = jsonObj.<strong>keys()</strong>;
         Student student;
         while(keys.hasNext()) {
            String key = (String) keys.next();
            student = new Student(key, jsonObj.<strong>optInt</strong>(key));
            list.add(student);
         }
         <strong>Collections.sort</strong>(list, new <strong>Comparator<Student>()</strong> {
<strong>            @Override
</strong>            public int <strong>compare</strong>(Student s1, Student s2) {
               return Integer.<strong>compare</strong>(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();
      }
   }
}
<strong>// Student class
</strong>class Student {
   String username;
   int pwd;
   Student(String username, int pwd) {
      this.username = username;
      this.pwd = pwd;
   }
}

Output

<strong>The values of JSONObject in the descending order:</strong><strong>
</strong><strong>789
456
123
111
</strong>
Updated on: 2020-02-18T10:07:15+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements