package com.run.horus.earlywaring.common;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class SortJsonArray {
public static JSONArray sortJsonArray(JSONArray array){
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < array.size(); i++) {
jsonValues.add(array.getJSONObject(i));
}
Collections.sort(jsonValues, new Comparator<JSONObject>() {
// You can change "Name" with "ID" if you want to sort by ID
private static final String KEY_NAME = "ID";
@Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
// 这里是a、b需要处理的业务,需要根据你的规则进行修改。
String aStr = a.getString(KEY_NAME);
valA = aStr.replaceAll("-", "");
String bStr = b.getString(KEY_NAME);
valB = bStr.replaceAll("-", "");
} catch (JSONException e) {
// do something
}
return -valA.compareTo(valB);
// if you want to change the sort order, simply use the following:
// return -valA.compareTo(valB);
}
});
for (int i = 0; i < array.size(); i++) {
sortedJsonArray.add(jsonValues.get(i));
}
return sortedJsonArray;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class SortJsonArray {
public static JSONArray sortJsonArray(JSONArray array){
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < array.size(); i++) {
jsonValues.add(array.getJSONObject(i));
}
Collections.sort(jsonValues, new Comparator<JSONObject>() {
// You can change "Name" with "ID" if you want to sort by ID
private static final String KEY_NAME = "ID";
@Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
// 这里是a、b需要处理的业务,需要根据你的规则进行修改。
String aStr = a.getString(KEY_NAME);
valA = aStr.replaceAll("-", "");
String bStr = b.getString(KEY_NAME);
valB = bStr.replaceAll("-", "");
} catch (JSONException e) {
// do something
}
return -valA.compareTo(valB);
// if you want to change the sort order, simply use the following:
// return -valA.compareTo(valB);
}
});
for (int i = 0; i < array.size(); i++) {
sortedJsonArray.add(jsonValues.get(i));
}
return sortedJsonArray;
}
}