• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
dwtfukgv
博客园    首页    新随笔    联系   管理    订阅  订阅
JSONArray 排序
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);

  

posted on 2019-01-09 19:14  dwtfukgv  阅读(463)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3