Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Java从JSONArray中删除重复对象并对其进行排序_Java_Json_Sorting - Fatal编程技术网

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

如何使用Java从JSONArray中删除重复对象并对其进行排序,java,json,sorting,Java,Json,Sorting,我的JSON是: [ { "distance":32, "stationCode":"MIG", "name":"Midghat", "platforms":"2" }, { "distance":32, "stationCode":"MIG", "name":"Midghat", "platforms":"2" }, { "distance":69,

我的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。我试着使用simple if else,但这个过程太多了。。有没有专门用于排序的快捷方式。

没有直接的方法,但您可以按照下面提到的方法进行操作:

  • 使用org.codehaus.jackson.map.ObjectMapper将JsonObject转换为Java对象列表

  • 使用Java映射使其唯一(put key=stationCode,javaObject作为对象)

  • 根据距离对地图数据进行排序


  • 我不久前编写了这个实用程序,它对
    JSONObjects的
    JSONArray
    进行排序 唯一的条件是
    JSONobjects
    必须包含要基于
    排序的
    键(如果要基于多个键排序,它还接受一组键)

    以下是使用ArrayList..contains()方法连接'2'JSONArray并从连接的JSONArray中删除重复项的代码:
    导入java.util.ArrayList;
    导入java.util.List;
    导入org.json.JSONArray;
    导入org.json.JSONException;
    导入org.json.JSONObject;
    /**
    *@author RAM K K
    *@gmailkkram523@gmail.com
    * 
    */
    公共类JSONOperations{
    公共静态void main(字符串[]args){
    字符串s3;
    目前,除除“姓名”以外的其他一些学校名称::,,,,,,,,,,,,,,,,,,,,“姓名”名称::,,,,,,,,,,,,,,,,,,,,,,除除除除“名称”名称::,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,);
    字符串s2=“[{\'name\':\'Mack\',\'car\':\'VW\',{\'name\':\'Steve\',\'car\':\'Mercedes-Benz\',{\'name\':'Bob\',\'car\':'Ford\'”;
    试一试{
    JSONArray sourceArray=新的JSONArray(s2);
    JSONArray destinationArray=新的JSONArray(s1);
    System.out.println(sourceArray);
    系统输出打印LN(目标阵列);
    对于(int i=0;i
    发布您尝试过的代码和错误:)这样您可以更容易地学习,我们也可以帮助您!当然有一种直接的排序方法:)谢谢,它对排序起了作用。。过滤重复了我的另一个逻辑:)通过排序节省了很多时间:)@GovindMantri,酷伙计,只要你知道你可以用多个键对DEC进行排序。这不符合问题的要求。“我希望它能根据距离排序,并删除重复的stationCode。”此外,你还可以重复发布。请参阅主题行“如何使用Java从JSONArray中删除重复的对象并对其进行排序”,这不是网站的工作方式。题目只是一个介绍。此外,即使网站是这样工作的,它也只是强化了我的观点,因为你的代码没有显示如何对列表进行排序。是的,我的代码不是用来排序的,而是用来删除重复项的!
    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");
    
    Here is the code for joining '2' JSONArrays and removing duplicates from the joined JSONArray, using ArrayList<String>..contains() method:
    
        import java.util.ArrayList;
        import java.util.List;
    
        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;
    
        /**
         * @author RAM K K
         * @gmail kkram523@gmail.com
         * 
         */
    
    public class JSONOperations {
    
        public static void main(String[] args) {
    
            String s3;
    
            String s1 = "[{\"name\": \"Bob\", \"car\": \"Ford\"},{\"name\": \"Steve\", \"car\": \"Mercedes Benz\"},{\"name\": \"Bob\", \"car\": \"Ford\"},{\"name\": \"Bob\", \"car\": \"Ford\"},{\"name\": \"Bob\", \"car\": \"Ford\"},{\"name\": \"Bob\", \"car\": \"Ford\"},{\"name\": \"Mary\", \"car\": \"Fiat\"}]";
            String s2 = "[{\"name\": \"Mack\", \"car\": \"VW\"},{\"name\": \"Steve\", \"car\": \"Mercedes Benz\"},{\"name\": \"Bob\", \"car\": \"Ford\"}]";
            try {
                JSONArray sourceArray = new JSONArray(s2);
                JSONArray destinationArray = new JSONArray(s1);
    
                System.out.println(sourceArray);
                System.out.println(destinationArray);
    
                for (int i = 0; i < sourceArray.length(); i++) {
                    destinationArray.put(sourceArray.getJSONObject(i));
                }
    
                System.out.println(destinationArray);
                System.out.println("JSONArray Size is: " + destinationArray.length());
                List<String> list = new ArrayList<String>();
                for (int i = 0; i < destinationArray.length(); i++) {
                    if (!list.contains(destinationArray.get(i).toString())) {
                        list.add(destinationArray.get(i).toString());
                    }
                }
    
                System.out.println("LIST: " + list);
                System.out.println("LIST Size: " + list.size());
    
                JSONArray distinctJSONArray = new JSONArray(list.toString());
                System.out.println(distinctJSONArray.length());
                for (int i = 0; i < distinctJSONArray.length(); i++) {
                    JSONObject JSON = (JSONObject) distinctJSONArray.getJSONObject(i);
                    System.out.println(JSON);
                }
    
                s1 = s1.substring(s1.indexOf("[") + 1, s1.lastIndexOf("]"));
                s2 = s2.substring(s2.indexOf("[") + 1, s2.lastIndexOf("]"));
    
                s3 = "[" + s1 + "," + s2 + "]";
                System.out.println(new JSONArray(s3));
    
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    
    }