我已经找了一段时间,想要一种像这样对 JSON 对象进行排序的方法:
{"results": [
{
"layerId": 5,
"layerName": "Pharmaceutical Entities",
"attributes": {
"OBJECTID": "35",
"FACILITYTYPE": "Pharmacy",
"FACILITYSUBTYPE": "24 Hr Pharmacy",
"COMMERCIALNAME_E": "SADD MAARAB PHARMACY"
},
"geometryType": "esriGeometryPoint",
},
{
"layerId": 5,
"layerName": "Pharmaceutical Entities",
"attributes": {
"OBJECTID": "1",
"FACILITYTYPE": "Pharmacy",
"FACILITYSUBTYPE": "24 Hr Pharmacy",
"COMMERCIALNAME_E": "GAYATHY HOSPITAL PHARMACY"
},
"geometryType": "esriGeometryPoint",
},
{
"layerId": 5,
"layerName": "Pharmaceutical Entities",
"attributes": {
"OBJECTID": "255",
"FACILITYTYPE": "Pharmacy",
"FACILITYSUBTYPE": "24 Hr Pharmacy",
"COMMERCIALNAME_E": "AL DEWAN PHARMACY"
},
"geometryType": "esriGeometryPoint",
}
]}
并按“COMMERCIALNAME_E”的值的字母顺序排序以获得:
{"results": [
{
"layerId": 5,
"layerName": "Pharmaceutical Entities",
"attributes": {
"OBJECTID": "255",
"FACILITYTYPE": "Pharmacy",
"FACILITYSUBTYPE": "24 Hr Pharmacy",
"COMMERCIALNAME_E": "AL DEWAN PHARMACY"
},
"geometryType": "esriGeometryPoint"
},
{
"layerId": 5,
"layerName": "Pharmaceutical Entities",
"attributes": {
"OBJECTID": "1",
"FACILITYTYPE": "Pharmacy",
"FACILITYSUBTYPE": "24 Hr Pharmacy",
"COMMERCIALNAME_E": "GAYATHY HOSPITAL PHARMACY"
},
"geometryType": "esriGeometryPoint"
},
{
"layerId": 5,
"layerName": "Pharmaceutical Entities",
"attributes": {
"OBJECTID": "35",
"FACILITYTYPE": "Pharmacy",
"FACILITYSUBTYPE": "24 Hr Pharmacy",
"COMMERCIALNAME_E": "SADD MAARAB PHARMACY"
},
"geometryType": "esriGeometryPoint"
}
]}
我找不到任何代码可以执行此操作。谁能给我一些帮助?
最佳答案
我使用 JSON 简单 API 对其进行排序。这是我的代码:
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class SortJSON {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONObject o = (JSONObject) parser.parse(new FileReader("test3.json"));
JSONArray array = (JSONArray) o.get("results");
ArrayList<JSONObject> list = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
list.add((JSONObject) array.get(i));
}
Collections.sort(list, new MyJSONComparator());
for (JSONObject obj : list) {
System.out.println(((JSONObject) obj.get("attributes")).get("OBJECTID"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyJSONComparator implements Comparator<JSONObject> {
@Override
public int compare(JSONObject o1, JSONObject o2) {
String v1 = (String) ((JSONObject) o1.get("attributes")).get("COMMERCIALNAME_E");
String v3 = (String) ((JSONObject) o2.get("attributes")).get("COMMERCIALNAME_E");
return v1.compareTo(v3);
}
}
关于java - 如何在java中对JSON对象进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4277715/