Java Android - 如何根据键对 JSONArray 进行排序

Jho*_*val 2 java arrays sorting android json

我将这个字符串(来自网络服务)放入这样的 JSONArray 中,

[
 {
  "lat": "-16.408545",
  "lon": "-71.539105",
  "type": "0",
  "distance": "0.54"
 },
 {
  "lat": "-16.4244317845",
  "lon": "-71.52562186",
  "type": "1",
  "distance": "1.87"
 },
 {
  "lat": "-16.4244317845",
  "lon": "-71.52562186",
  "type": "1",
  "distance": "0.22"
 }
]
Run Code Online (Sandbox Code Playgroud)

我需要按距离键对其进行排序以显示最近的第一个和最远的最后一个。我没有尝试任何代码,因为我真的没有任何想法。我没有使用 GSON 库,我使用的是org.json.JSONArray.

cry*_*sis 6

首先在列表中解析您的数组

JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
    jsonList.add(jsonArray.getJSONObject(i));
}
Run Code Online (Sandbox Code Playgroud)

然后使用 collection.sort 对新创建的列表进行排序

Collections.sort( jsonList, new Comparator<JSONObject>() {

    public int compare(JSONObject a, JSONObject b) {
        String valA = new String();
        String valB = new String();

        try {
            valA = (String) a.get("distance");
            valB = (String) b.get("distance");
        } 
        catch (JSONException e) {
            //do something
        }

        return valA.compareTo(valB);
    }
});
Run Code Online (Sandbox Code Playgroud)

在数组中插入排序的值

for (int i = 0; i < jsonArray.length(); i++) {
    sortedJsonArray.put(jsonList.get(i));
}
Run Code Online (Sandbox Code Playgroud)