zoukankan      html  css  js  c++  java
  • JSONArray排序[收藏]

    问题

    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);
    

    原文地址

  • 相关阅读:
    urlrewrite地址重写的使用
    算法学习
    数据库之Case When
    速卖通返回503错误
    概述:软件开发工具
    c#将List&lt;T&gt;转换成DataSet
    表单域规范写法
    ant打包和jar包混淆
    Node.js文档和教程
    webpack开发和生产两个环境的配置详解
  • 原文地址:https://www.cnblogs.com/52liming/p/9585374.html
Copyright © 2011-2022 走看看