java - 如何使用 Java 从 JSONArray 中删除重复对象并对其进行排序

标签 java json sorting

我的 JSON 是:

[
   {
      "distance":32,
      "stationCode":"MIG",
      "name":"Midghat",
      "platforms":"2"
   },
   {
      "distance":32,
      "stationCode":"MIG",
      "name":"Midghat",
      "platforms":"2"
   },
   {
      "distance":69,
      "stationCode":"MDDP",
      "name":"Mandideep",
      "platforms":"2"
   },
   {
      "distance":69,
      "stationCode":"MDDP",
      "name":"Mandideep",
      "platforms":"2"
   },
   {
      "distance":18,
      "stationCode":"HBD",
      "name":"Hoshangabad",
      "platforms":"2"
   },
   {
      "distance":18,
      "stationCode":"HBD",
      "name":"Hoshangabad",
      "platforms":"2"
   },
   {
      "distance":37,
      "stationCode":"CHQ",
      "name":"Choka",
      "platforms":"2"
   },
   {
      "distance":37,
      "stationCode":"CHQ",
      "name":"Choka",
      "platforms":"2"
   },
   {
      "distance":85,
      "stationCode":"HBJ",
      "name":"Habibganj",
      "platforms":"5"
   },
   {
      "distance":85,
      "stationCode":"HBJ",
      "name":"Habibganj",
      "platforms":"5"
   },
   {
      "distance":0,
      "stationCode":"ET",
      "name":"ItarsiJn",
      "platforms":"28"
   },
   {
      "distance":8,
      "stationCode":"PRKD",
      "name":"Powerkheda",
      "platforms":"2"
   },
   {
      "distance":8,
      "stationCode":"PRKD",
      "name":"Powerkheda",
      "platforms":"2"
   },
   {
      "distance":55,
      "stationCode":"ODG",
      "name":"ObaidullaGanj",
      "platforms":"2"
   },
   {
      "distance":55,
      "stationCode":"ODG",
      "name":"ObaidullaGanj",
      "platforms":"2"
   },
   {
      "distance":44,
      "stationCode":"BKA",
      "name":"Barkhera",
      "platforms":"2"
   },
   {
      "distance":44,
      "stationCode":"BKA",
      "name":"Barkhera",
      "platforms":"2"
   },
   {
      "distance":79,
      "stationCode":"MSO",
      "name":"Misrod",
      "platforms":"2"
   },
   {
      "distance":79,
      "stationCode":"MSO",
      "name":"Misrod",
      "platforms":"2"
   },
   {
      "distance":25,
      "stationCode":"BNI",
      "name":"Budni",
      "platforms":"2"
   },
   {
      "distance":25,
      "stationCode":"BNI",
      "name":"Budni",
      "platforms":"2"
   },
   {
      "distance":91,
      "stationCode":"BPL",
      "name":"BhopalJn",
      "platforms":"6"
   },
   {
      "distance":63,
      "stationCode":"ITKL",
      "name":"ItayaKalan",
      "platforms":"2"
   },
   {
      "distance":63,
      "stationCode":"ITKL",
      "name":"ItayaKalan",
      "platforms":"2"
   }
]

我希望它根据距离排序并删除重复的 stationCode。我尝试使用简单的 if else,但该过程会太多.. 任何专门用于排序的快捷方式。

最佳答案

我不久前写了这个实用程序,它对 JSONObjectsJSONArray 进行排序 唯一的条件是你的 JSONobjects 必须包含你想要排序(如果你想排序,它也接受一组键基于几个键)

import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JSONArraySort {
    @SuppressWarnings("unchecked")
    public static void sortASCE(JSONArray array, Object key) {
        Object[] keys = { key };
        Collections.sort(array, new JSONArrayComparator(false, keys));
    }
    @SuppressWarnings("unchecked")
    public static void sortDESC(JSONArray array, Object key) {
        Object[] keys = { key };
        Collections.sort(array, new JSONArrayComparator(true, keys));
    }
    @SuppressWarnings("unchecked")
    public static void sortASCE(JSONArray array, Object[] key) {
        Collections.sort(array, new JSONArrayComparator(false, key));
    }
    @SuppressWarnings("unchecked")
    public static void sortDESC(JSONArray array, Object[] key) {
        Collections.sort(array, new JSONArrayComparator(true, key));
    }
    private static class JSONArrayComparator implements Comparator<JSONObject> {
        private final Object[] KEYS;
        private final boolean DESC;
        public JSONArrayComparator(boolean DESC, Object[] KEYS) {
            this.KEYS = KEYS;
            this.DESC = DESC;
        }
        @Override
        public int compare(JSONObject object1, JSONObject object2) {
            int length = KEYS.length;
            for(int i = 0 ; i < length ; i++){
                String KEY = KEYS[i].toString();
                Object one = object1.get(KEY);
                Object two = object2.get(KEY);
                if(Number.class.isAssignableFrom(one.getClass()) && Number.class.isAssignableFrom(two.getClass())){
                    Double numOne = Number.class.cast(one).doubleValue();
                    Double numTwo = Number.class.cast(two).doubleValue();
                    int compared = 0;
                    if(DESC){
                        compared = numTwo.compareTo(numOne);
                    }else{
                        compared = numOne.compareTo(numTwo);
                    }
                    if(i == KEYS.length - 1 || compared != 0){
                        return compared;
                    }
                }else{
                    int compared = 0;
                    if(DESC){
                        compared = two.toString().compareTo(one.toString());
                    }else{
                        compared = one.toString().compareTo(two.toString());
                    }
                    if(i == KEYS.length - 1 || compared != 0){
                        return compared;
                    }
                }
            }
            // this shouldn't happen.
            return 0;
        }
    }
        //testing...
    public static void main(String... args) {
        JSONArray array1 = new JSONArray();
        for(int i = 0 ; i < 100 ; i++){
            Random random = new Random();
            int num1 = random.nextInt(10);
            int num2 = random.nextInt(10);
            JSONObject object = new JSONObject();
            object.put("num1", num1);
            object.put("num2", num2);
            array1.add(object);
        }
        String[] keys = { "num1", "num2" };
        sortASCE(array1, keys);
        System.out.println(array1.toString());
    }
}

现在如果你想删除重复项,你可以通过它们迭代

Set<String> stationCodes=new HashSet<String>();
JSONArray tempArray=new JSONArray();
for(int i=0;i<yourJSONArray.size();i++){
   String  stationCode=yourJSONArray.getJSONObject(i).getString("stationCode");
   if(stationsCodes.contains(stationCode){
     continue;
   }
   else{
      stationsCodes.add(stationCode);
      tempArray.add(yourJSONArray.getJSONObject(i));
   }

}


yourJSONArray= tempArray; //assign temp to original

//here how you can sort it using utility above:
JSONArraySort.sortASCE(yourJSONArray,"distance");

关于java - 如何使用 Java 从 JSONArray 中删除重复对象并对其进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32371236/

相关文章:

javascript - 如何使用 Lodash 按子数组的属性进行排序

java - Swing:非输入文本字段

java - 合并/相交两个集合而不改变其中一个集合

java - 从 php 检测 web 服务器上是否安装了 java

java - 从 Java 客户端调用 Web 服务

javascript - PHP json_encode 在字符串末尾加一个1

javascript - 如何加快 JSON 日期解析速度?

ios - Error Domain=NSCocoaErrorDomain Code=3840 是属于服务器端还是本地代码端?

无法按字母顺序(排序)字符串吗?

java - 从文本文件中读取行并将它们排序到链接列表中java