如何在 Java 中对 JSONObject 进行排序?
JSONObject 是无序集合,其中包含键值对,并且这些值可以是boolean、JSONArray、JSONObject、number和string等任何类型。JSONObject 的构造函数可用于将外部形式的 JSON 文本转换为内部形式,其值可以用get()和opt() 方法检索,或使用put()和toString()方法将值转换为 JSON 文本。
在下面的示例中,我们可以按降序对 JSONObject 的值进行排序。
示例
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;
}
}输出
The values of JSONObject in the descending order: 789 456 123 111
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP