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

Java Android - How to sort a JSONArray based on keys

我正在将这个字符串(来自网络服务)放入 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"
 }
]

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

将您的 json 对象解析为模型(例如数组列表)并使用比较器对其进行排序。

ArrayList<ClassObject> dataList = new ArrayList<String>();
JSONArray array = new JSONArray(json);     
for(Object obj : jsonArray){
   dataList.add(//your data model);
}

数组列表排序请参考此link http://java2novice.com/java-collections-and-util/arraylist/sort-comparator/

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

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

然后使用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);
    }
});

将排序后的值插入数组

for (int i = 0; i < jsonArray.length(); i++) {
    sortedJsonArray.put(jsonList.get(i));
}

试试这个。它应该工作

ArrayList<JSONObject> array = new ArrayList<JSONObject>();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
   try {
       array.add(jsonArray.getJSONObject(i));
   } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
}   

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

@Override
public int compare(JSONObject lhs, JSONObject rhs) {
    // TODO Auto-generated method stub

    try {
        return (lhs.getDouble("distance").compareTo(rhs.getDouble("distance")));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return 0;
    }
}
});

然后你可以将排序后的 ArrayList array 转换成 JSONArray.

JSONArray jsonArray = new JSONArray(array);
String jsonArrayStr = jsonArray.toString();