gpt4 book ai didi

java - 如何在 JAVA 中对 JSONArray 进行排序

转载 作者:IT老高 更新时间:2023-10-28 12:55:01 26 4
gpt4 key购买 nike

如何按对象的字段对 JSONArray 对象进行排序?

输入:

[
{ "ID": "135", "Name": "Fargo Chan" },
{ "ID": "432", "Name": "Aaron Luke" },
{ "ID": "252", "Name": "Dilip Singh" }
];

所需的输出(按“名称”字段排序):

[
{ "ID": "432", "Name": "Aaron Luke" },
{ "ID": "252", "Name": "Dilip Singh" }
{ "ID": "135", "Name": "Fargo Chan" },
];

最佳答案

试试这个:

    //I assume that we need to create a JSONArray object from the following string
String jsonArrStr = "[ { \"ID\": \"135\", \"Name\": \"Fargo Chan\" },{ \"ID\": \"432\", \"Name\": \"Aaron Luke\" },{ \"ID\": \"252\", \"Name\": \"Dilip Singh\" }]";

JSONArray jsonArr = new JSONArray(jsonArrStr);
JSONArray sortedJsonArray = new JSONArray();

List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
Collections.sort( jsonValues, new Comparator<JSONObject>() {
//You can change "Name" with "ID" if you want to sort by ID
private static final String KEY_NAME = "Name";

@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) {
//do something
}

return valA.compareTo(valB);
//if you want to change the sort order, simply use the following:
//return -valA.compareTo(valB);
}
});

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

排序后的 JSONArray 现在存储在 sortedJsonArray 对象中。

关于java - 如何在 JAVA 中对 JSONArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19543862/

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