What is the method for sorting JSONObject in Java?
In Java, a JSONObject is an unordered collection of key-value pairs that does not support direct sorting. However, you can convert the key-value pairs in a JSONObject into a List and then sort the List.
The following is an example code that converts key-value pairs in a JSONObject to a List and sorts them.
import org.json.JSONObject;
import java.util.*;
public class Main {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John");
jsonObject.put("age", 30);
jsonObject.put("city", "New York");
// 将JSONObject中的键值对转换为List
List<Map.Entry<String, Object>> entries = new ArrayList<>(jsonObject.toMap().entrySet());
// 对List进行排序
Collections.sort(entries, new Comparator<Map.Entry<String, Object>>() {
public int compare(Map.Entry<String, Object> entry1, Map.Entry<String, Object> entry2) {
return entry1.getKey().compareTo(entry2.getKey());
}
});
// 打印排序后的键值对
for (Map.Entry<String, Object> entry : entries) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
The output result:
age: 30
city: New York
name: John
In the example, we first convert the key-value pairs in the JSONObject into a List, then use the Collections.sort method to sort the List, and finally iterate through the sorted List to print the key-value pairs. In the comparison function, we use entry1.getKey().compareTo(entry2.getKey()) to compare the size of the keys, thus achieving sorting by keys.