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

前端之家收集整理的这篇文章主要介绍了对jsonArray数组存储的对象做自定义按多个值排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

});

}

猜你在找的Json相关文章