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++) {
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"}]