首先加JSONArray转成JSONObject的List
List<JSONObject> jsonObjectList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
jsonObjectList.add(jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
对这个List进行排序
Collections.sort(jsonObjectList, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject jsonA, JSONObject jsonB) {
String keyName = "Value";
int sort = 1;//1降序 -1升序
String strA = jsonA.optString(keyName);
String strB = jsonB.optString(keyName);
float f1 = Float.parseFloat(strA);
float f2 = Float.parseFloat(strB);
if(f1 > f2){
return 1*sort;
}else if(f1 < f2){
return -1*sort;
}else{
return 0;
}
}});
将List转换成JSONArray返回
if(jsonObjectList.size() != jsonArray.length())
return;
for (int i = 0; i < jsonObjectList.size(); i++) {
try {
jsonArray.put(i,jsonObjectList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}