简体   繁体   中英

Sorting ArrayList of JSONObjects not working properly

I have a JSONArray called events. I need these events to be sorted by a field called "EVENT_TIME" in descending order. I store the events into an ArrayList called all_events and use Collections.sort() on it with my own comparator. Out of 6 events , 5 get sorted and 1 is in the wrong place.

I end up with:

Acceptance 31-May-2014 10:31:00
Reopened 31-May-2014 10:30:55
Arrived at Pickup Location 31-May-2014 10:30:45
Unloaded from Vessel 31-May-2014 10:30:00
Shipment Create 29-May-2014 00:00:00
Arrive Load Port 30-May-2014 00:00:00

after sorting. Clearly the last one is in the wrong place.

Storing into arraylist and calling the sort:

ArrayList<String>all_events=new ArrayList<String>();
for(int i=0;i<events.length();i++){
    JSONObject event=events.getJSONObject(i);
    all_events.add(event.toString());
}
Collections.sort(all_events, new JSONComparator());;

The JSONComparator class:

class JSONComparator implements Comparator<String>{

        public int compare(String a, String b){
            String a_time=null;
            String b_time=null;
            try{
                JSONObject event1=new JSONObject(a);
                JSONObject event2=new JSONObject(b);
                a_time=event1.getString("EVENT_TIME");
                b_time=event2.getString("EVENT_TIME");
            }
            catch(JSONException e){
                e.printStackTrace();
            }
            SimpleDateFormat sdf=new SimpleDateFormat("ss-MMM-yyyy HH:mm:sss");
            Date date1=null, date2=null;
            try{
                date1=sdf.parse(a_time);
                date2=sdf.parse(b_time);
            }
            catch(ParseException pe){
                pe.printStackTrace();
            }

            return date1.compareTo(date2)*-1;

        }

    };

printing the output:

for(int i=0;i<all_events.size();i++){
    JSONObject event=new JSONObject(all_events.get(i));
    String s=event.getString("EVENT_CODE");
    String eventname=codemap.getString(s);
    System.out.println(eventname+" "+event.getString("EVENT_TIME"));
}

ss-MMM-yyyy HH:mm:sss should be dd-MMM-yyyy HH:mm:ss .

Check out this link and for each letter's meaning in SimpleDateFormat check out Oracle's documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM