我们如何在 Java 中对 JSONArray 排序?
JSON 是一种应用广泛的数据交换格式,是轻量级的且与语言无关。JSONArray 可以解析来自 String 的文本以生成类似于矢量的对象,并支持 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++) {
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
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP