Uhm… ok since i still don‘t quite understand why you weren‘t able to utilize the method described in the link, i‘ll just modify the code you posted, so that it sorts it. (I assume „id“ should actually be „best“)
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.json.JSONException;
String[] names = { "A", "B", "C" };
JSONArray values;
void setup() {
values = new JSONArray();
for (int i = 0; i < names.length; i++) {
JSONObject exp = new JSONObject();
exp.setInt("id", (int)(Math.random()*10));
exp.setString("name", names[i]);
values.setJSONObject(i, exp);
}
JSONArray sorted = sort(values, "id", true); //change „id“ to „name“ to sort by name and 0 to 1 to reverse sort order
// id like to sort this descending by the id
}
void draw() {
}
JSONArray sort(JSONArray jsonArr, String sortBy, boolean sortOrder) {
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArr.size(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
final String KEY_NAME = sortBy;
final Boolean SORT_ORDER = sortOrder;
Collections.sort( jsonValues, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_NAME);
valB = (String) b.get(KEY_NAME);
}
catch (JSONException e) {
//exception
}
if (SORT_ORDER) {
return valA.compareTo(valB);
} else {
return -valA.compareTo(valB);
}
}
});
return sortedJsonArray;
}