gpt4 book ai didi

java - 如何对包含另一个 JSONObject 的 JSONObject 的 JSONArray 进行排序?

转载 作者:行者123 更新时间:2023-12-01 10:14:22 25 4
gpt4 key购买 nike

我能够对 JSONObject 的 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);
}

最佳答案

只需比较 lhs.getJSONObject("key3").getString("key4")rhs.getJSONObject("key3").getString("key4")

关于java - 如何对包含另一个 JSONObject 的 JSONObject 的 JSONArray 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35996976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com