我能够对JSONA的JSONArray进行排序,但是当我需要对数组进行排序时,我会陷入困境,如下所示:
[{
"key1": "value1",
"key2": "value2",
"key3": {
"key4": "value4",
"key5": "value5"
}
}, {
"key1": "value1",
"key2": "value2",
"key3": {
"key4": "value4",
"key5": "value5"
}
}]
我想在“Key4”上对此数组进行排序。
这是我在key1
上排序时的代码public static JSONArray sortJsonArray(JSONArray array, final String key) throws JSONException
{
List<JSONObject> jsons = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject lhs, JSONObject rhs) {
String lid = null;
String rid = null;
try {
lid = lhs.getString(key);
rid = rhs.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
// Here you could parse string id to integer and then compare.
return lid.compareTo(rid);
}
});
return new JSONArray(jsons);
}
答案 0 :(得分:1)
只需将lhs.getJSONObject("key3").getString("key4")
与rhs.getJSONObject("key3").getString("key4")
进行比较即可。
答案 1 :(得分:0)
粘贴我的代码在这里(根据@ cricket_007帮助),这可以帮助其他人:
public static JSONArray sortJsonArrayOpenDate(JSONArray array) throws JSONException {
List<JSONObject> jsons = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject lhs, JSONObject rhs) {
String lid = null;
String rid = null;
try {
lid = lhs.getJSONObject("key3").getString("key4");
rid = rhs.getJSONObject("key3").getString("key4");
} catch (JSONException e) {
e.printStackTrace();
}
return lid.compareTo(rid);
}
});
return new JSONArray(jsons);
}