我们如何在Java中对JSONObject进行排序?
甲的JSONObject 是无序 一个收集键,值对,并且这些值可以是任何这些类型等的布尔,JSONArray,JSONObject的,数量和字符串。JSONObject的构造函数可用于将外部形式的JSON文本转换为内部形式,其内部值可以使用get()和opt() 方法进行检索,也可以使用put()和toString()方法。
在下面的示例中,我们可以按降序对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 classclass 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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便