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;
}
}
本文介绍了一种使用Java实现的对JSON数组进行排序的方法。通过将JSONArray转换为List并利用Collections.sort()方法配合自定义Comparator来完成排序过程。该方法允许按特定键(如ID)的值进行升序或降序排列。
495

被折叠的 条评论
为什么被折叠?



