加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

JSONArray 排序

发布时间:2020-12-16 19:34:28 所属栏目:百科 来源:网络整理
导读:JSONObject o1 = JSONObject. parSEObject ( "{ " id " :1, " name " : " ljw " }" ) ; JSONObject o2 = JSONObject. parSEObject ( "{ " id " :3, " name " : " ljw " }" ) ; JSONObject o3 = JSONObject. parSEObject ( "{ " id " :2, " na
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);

结果:

排序前:[{"id":1,"name":"ljw"},{"id":3,{"id":2,"name":"ljw"}] 排序后:[{"id":1,"name":"ljw"}]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读