甲的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