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

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

发布时间:2020-12-16 18:57:38 所属栏目:百科 来源:网络整理
导读:public void batchRepayment() throws IOException{ String jsonString = "[{ "orderId": "431","installment": "9" },{ "orderId": "135",{ "orderId": "432","installment": "8" },"installment": "2" },"installment": "5" }

public void batchRepayment() throws IOException{

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


JSONArray jsonArray = JSONArray.fromObject(jsonString);
if(jsonArray != null){
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.size(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
//重写排序方法,按照order by orderId,installment方式排序,确保同个订单orderId优先还期数installment靠前的
Collections.sort( jsonList,new Comparator<JSONObject>() {
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;
}
}

});

}

(编辑:李大同)

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

    推荐文章
      热点阅读