问题

JSONArray中嵌套JSONObject, 对JSONArray进行排序

排序前:

[{"id":1,"name":"ljw"},{"id":3,"name":"ljw"},{"id":2,"name":"ljw"}]

排序后:

[{"id":1,"name":"ljw"},{"id":2,"name":"ljw"},{"id":3,"name":"ljw"}]

利用Collections.sort()

JSONObject o1 = JSONObject.parseObject("{\"id\":1,\"name\":\"ljw\"}");
JSONObject o2 = JSONObject.parseObject("{\"id\":3,\"name\":\"ljw\"}");
JSONObject o3 = JSONObject.parseObject("{\"id\":2,\"name\":\"ljw\"}");
JSONArray a = new JSONArray();
a.add(o1);
a.add(o2);
a.add(o3);
//转list 1
List<JSONObject> list = JSONArray.parseArray(a.toJSONString(), JSONObject.class);
//转list 2
//List<JSONObject> list = new ArrayList<JSONObject>();
//for (int i = 0; i < a.size(); i++) {
// list.add((JSONObject) a.get(i));
//}
System.out.println("排序前:"+a);
Collections.sort(list, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject o1, JSONObject o2) {
int a = o1.getInteger("id");
int b = o2.getInteger("id");
if (a > b) {
return 1;
} else if(a == b) {
return 0;
} else
return -1;
}
});
JSONArray jsonArray = JSONArray.parseArray(list.toString());
System.out.println("排序后:" + jsonArray);

原文地址

最新文章

  1. [转]【无私分享:ASP.NET CORE 项目实战(第九章)】创建区域Areas,添加TagHelper
  2. fir.im Weekly - iOS开发中的Git流程
  3. OC第九节——协议与代理
  4. 【leetcode】Insert Interval
  5. Greedy --- HNU 13320 Please, go first
  6. DNS报文格式
  7. docker commit容器
  8. MVC ViewData和ViewBag[转]
  9. 9.6. MySQL中保留字的处理
  10. HttpClient(4.3.5) - ResponseHandler
  11. [jquery]高级篇--标签选择
  12. Qt在表格中加入控件
  13. JS -- The Scope Chain 作用域链
  14. Android实现购物车功能
  15. 原型模式ProtoType
  16. 阿里云OSS下载pdf文件,并在pdf文件上添加水印
  17. elasticsearch 口水篇(1) 安装、插件
  18. python中的取整
  19. Net Web Api Route
  20. html转译字符 字符实体

热门文章

  1. Restframework 渲染器 render 组件实例-4
  2. day74天中间件介绍
  3. Datetimepicker.js用法
  4. LOJ#2052. 「HNOI2016」矿区(平面图转对偶图)
  5. jzoj5950
  6. cassandra用户名和密码的设置
  7. Pyplot绘图的格式
  8. day 48 ORM 进阶 多表连接 创建 以及 html模板继承
  9. 剑指offer三十三之丑数
  10. 搭建互联网架构学习--005--框架初步拆分ssm单一框架