阅读量:137
在Java中,JSONObject是一个无序的键值对集合,不支持直接排序。但是,你可以将JSONObject中的键值对转换为List,然后对List进行排序。
以下是通过将JSONObject中的键值对转换为List并进行排序的示例代码:
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
输出结果:
age: 30
city: New York
name: John
在示例中,首先将JSONObject中的键值对转换为List,然后使用Collections.sort方法对List进行排序,最后遍历排序后的List打印键值对。在比较函数中,我们使用了entry1.getKey().compareTo(entry2.getKey())来比较键的大小,从而实现按键进行排序。