
JSON是广泛使用的数据交换格式之一,并且是一种轻量级和 >语言独立。 JSONArray可以解析字符串中的文本以生成向量-类似对象,并支持java.util.List 接口。
我们可以在下面的示例中对 JSONArray 进行排序。
import java.util.*;
import org.json.*;
public class SortJSONArrayTest {
public static void main(String[] args) {
String jsonStr = "[ { \"ID\": \"115\", \"Name\": \"Raja\" },{ \"ID\": \"120\", \"Name\": \"Jai\" },{ \"ID\": \"125\", \"Name\": \"Adithya\" }]";
JSONArray jsonArray = new JSONArray(jsonStr);
JSONArray sortedJsonArray = new JSONArray();
List list = new ArrayList();
for(int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getJSONObject(i));
}
System.out.println("Before Sorted JSONArray: " + jsonArray);
Collections.sort(list, new Comparator() {
private static final String KEY_NAME = "Name";
@Override
public int compare(JSONObject a, JSONObject b) {
String str1 = new String();
String str2 = new String();
try {
str1 = (String)a.get(KEY_NAME);
str2 = (String)b.get(KEY_NAME);
} catch(JSONException e) {
e.printStackTrace();
}
return str1.compareTo(str2);
}
});
for(int i = 0; i < jsonArray.length(); i++) {
<strong> </strong>sortedJsonArray.put(list.get(i));
}
System.out.println("Sorted JSON Array with Name: " + sortedJsonArray);
}
}Before Sorted JSONArray:
[{"ID":"115","Name":"Raja"},
{"ID":"120","Name":"Jai"},
{"ID":"125","Name":"Adithya"}]
Sorted JSON Array with Name:
[{"ID":"125","Name":"Adithya"},
{"ID":"120","Name":"Jai"},
{"ID":"115","Name":"Raja"}]以上就是我们如何在Java中对JSONArray进行排序?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号