对jsonArray数组存储的对象做自定义按多个值排序

 public void batchRepayment() throws IOException{

  String jsonString = "[{ \"orderId\": \"431\", \"installment\": \"9\" }, { \"orderId\": \"135\", \"installment\": \"9\" },{ \"orderId\": \"432\", \"installment\": \"9\" },{ \"orderId\": \"135\", \"installment\": \"8\" },{ \"orderId\": \"135\", \"installment\": \"2\" },{ \"orderId\": \"432\", \"installment\": \"5\" },{ \"orderId\": \"431\", \"installment\": \"3\" }]";


        JSONArray jsonArray = JSONArray.fromObject(jsonString);
        if(jsonArray != null){
           List jsonList = new ArrayList();
           for (int i = 0; i < jsonArray.size(); i++) {
                jsonList.add(jsonArray.getJSONObject(i));
           }
           //重写排序方法,按照order by orderId,installment方式排序,确保同个订单orderId优先还期数installment靠前的
           Collections.sort( jsonList, new Comparator() {
               private static final String KEY_NAME = "orderId";
               private static final String KEY_NAME2 = "installment";

               @Override
               public int compare(JSONObject a, JSONObject b) {
                   String valA_1 = new String();
                   String valB_1 = new String();
                   String valA_2 = new String();
                   String valB_2 = new String();

                   try {
                       valA_1 =  a.getString(KEY_NAME);
                       valB_1 =  b.getString(KEY_NAME);
                       valA_2 =  a.getString(KEY_NAME2);
                       valB_2 =  b.getString(KEY_NAME2);
                   }catch (JSONException e) {
                       //do something
                   }
                   int flag = valA_1.compareTo(valB_1);
                   if(flag == 0){
                      return valA_2.compareTo(valB_2);
                   }else{
                      return flag;
                   }
               }

           });

}

你可能感兴趣的:(对jsonArray数组存储的对象做自定义按多个值排序)