简体   繁体   中英

Sort Java Objects Alphabetically to a JSON Object

Hello i hope someone can help,i wish to sort this list alphabetically into this json object but im having a bit of trouble with the logic.I was using a compareTo method as below but cant seem to get it to work(have tried a few different ways ,Thank you in advance to anyone who can help

      JSONObject practiceDetailsJson = new JSONObject();
         for (Practice practice : practices) {
            practice.getPracticeName().compareTo(obj2.getName());
            practiceDetailsJson.put("practiceName", practice.getPracticeName());
            practiceDetailsJson.put("practiceCode", practice.getPracticeCode());
            practiceDetailsJson.put("practiceId", practice.getRowid());
            practicesAsJSON.add(practiceDetailsJson);
            }
        }

You can try to create a comparator here.

class PracticeComparator implements Comparator<Practice> {
           @Override
           public int compare(Practice p1, Practice p2) {

                return p1.getPracticeName().compareTo(p2.getPracticeName());
           }
}

You can use this comparator like:-

Collections.sort(practices, new PracticeComparator());

Now you can again iterate over practices to convert it to JSON format.

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