首先需要引入 fastjson 的 jar 包
public static void main(String[] args) {JSONArray array &#61; new JSONArray();JSONObject obj1 &#61; new JSONObject();obj1.put("score",70);obj1.put("name","张三");array.add(obj1);JSONObject obj2 &#61; new JSONObject();obj2.put("score",80);obj2.put("name","李四");array.add(obj2);JSONObject obj3 &#61; new JSONObject();obj3.put("score",60);obj3.put("name","王五");array.add(obj3);JSONArray result &#61; jsonArraySort(array,"score",true);for (int i &#61; 0; i < result.size(); i&#43;&#43;) {System.out.println(result.getJSONObject(i).getString("name"));}
}
public static JSONArray jsonArraySort(JSONArray array, final String sortColName,final boolean isAsc) {JSONArray sortedJsonArray &#61; new JSONArray();List<JSONObject> jsonList &#61; new ArrayList<JSONObject>();for (int i &#61; 0; i < array.size(); i&#43;&#43;) {jsonList.add(array.getJSONObject(i));}Collections.sort(jsonList, new Comparator<JSONObject>() {&#64;Overridepublic int compare(JSONObject o1, JSONObject o2) {String valA &#61; o1.getString(sortColName);String valB &#61; o2.getString(sortColName);if (isAsc) {return valA.compareTo(valB);} else {return valB.compareTo(valA);}}});for(JSONObject obj : jsonList) {sortedJsonArray.add(obj);}return sortedJsonArray;
}
输出结果&#xff1a;
王五
张三
李四