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

    原文地址

  • 相关阅读:
    iOS各种证书
    Error No matching provisioning profiles found
    iOS 一个开发者账号 多台Mac 共用
    外中断(学习汇编)
    端口(学习汇编)
    8086CPU寄存器
    int指令(学习汇编)
    内中断(学习汇编)
    标志寄存器(学习汇编)
    CALL和RET指令(学习汇编)
  • 原文地址:https://www.cnblogs.com/52liming/p/9585374.html
Copyright © 2011-2022 走看看