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.


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);
            student = new Student(key, jsonObj.optInt(key));
         Collections.sort(list, new Comparator<Student>() {
            public int compare(Student s1, Student s2) {
               return, s1.pwd);
         System.out.println("The values of JSONObject in the descending order:");
         for(Student s : list) {
      } catch(JSONException e) {
// 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:

Updated on: 18-Feb-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started