加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何使用Java从JSONArray中删除重复和排序对象

发布时间:2020-12-15 01:03:32 所属栏目:Java 来源:网络整理
导读:我的JSON是: [ { "distance":32,"stationCode":"MIG","name":"Midghat","platforms":"2" },{ "distance":32,{ "distance":69,"stationCode":"MDDP","name":"Mandideep",{ "distance":18,"stationCode":"HBD","name":"Hoshangabad",{ "distance":37,"station

我的JSON是:

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

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

最佳答案
我不久前编写了这个实用程序,它对JSONArray的JSONArray进行了排序
唯一的条件是你的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,new JSONArrayComparator(true,keys));
    }
    @SuppressWarnings("unchecked")
    public static void sortASCE(JSONArray array,Object[] key) {
        Collections.sort(array,key));
    }
    @SuppressWarnings("unchecked")
    public static void sortDESC(JSONArray array,key));
    }
    private static class JSONArrayComparator implements Comparator

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

Set

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读