【问题标题】:How can I sort a JSONArray in JAVA [duplicate]如何在 JAVA 中对 JSONArray 进行排序 [重复]
【发布时间】:2013-10-23 14:01:52
【问题描述】:

如何按对象的字段对对象的 JSONArray 进行排序?

输入:

[
    { "ID": "135", "Name": "Fargo Chan" },
    { "ID": "432", "Name": "Aaron Luke" },
    { "ID": "252", "Name": "Dilip Singh" }
];

所需的输出(按“名称”字段排序):

[
    { "ID": "432", "Name": "Aaron Luke" },
    { "ID": "252", "Name": "Dilip Singh" }
    { "ID": "135", "Name": "Fargo Chan" },
];

【问题讨论】:

  • 我想根据“名称”进行排序。输出应该是:432 Aaron Luke 252 Dilip Singh 135 Fargo Chan

标签: java json sorting


【解决方案1】:

试试这个:

    //I assume that we need to create a JSONArray object from the following string
    String jsonArrStr = "[ { \"ID\": \"135\", \"Name\": \"Fargo Chan\" },{ \"ID\": \"432\", \"Name\": \"Aaron Luke\" },{ \"ID\": \"252\", \"Name\": \"Dilip Singh\" }]";

    JSONArray jsonArr = new JSONArray(jsonArrStr);
    JSONArray sortedJsonArray = new JSONArray();

    List<JSONObject> jsonValues = new ArrayList<JSONObject>();
    for (int i = 0; i < jsonArr.length(); i++) {
        jsonValues.add(jsonArr.getJSONObject(i));
    }
    Collections.sort( jsonValues, new Comparator<JSONObject>() {
        //You can change "Name" with "ID" if you want to sort by ID
        private static final String KEY_NAME = "Name";

        @Override
        public int compare(JSONObject a, JSONObject b) {
            String valA = new String();
            String valB = new String();

            try {
                valA = (String) a.get(KEY_NAME);
                valB = (String) b.get(KEY_NAME);
            } 
            catch (JSONException e) {
                //do something
            }

            return valA.compareTo(valB);
            //if you want to change the sort order, simply use the following:
            //return -valA.compareTo(valB);
        }
    });

    for (int i = 0; i < jsonArr.length(); i++) {
        sortedJsonArray.put(jsonValues.get(i));
    }

排序后的 JSONArray 现在存储在 sortedJsonArray 对象中。

【讨论】:

  • 感谢您的回答。帮助很大。
  • 感谢您的回答。最后我不需要for循环。
  • 我知道这行得通,但是很糟糕,我们不得不求助于这样的东西来重用排序函数,因为知道 JsonArray 包含作为集合 private final List&lt;JsonElement&gt; elements 的项目,但是是私有的!
  • 很好的答案,但这不会忽略大小写(A>B>C>a)
  • 忘记为以后的我和其他人添加 - 只需将其更改为 compareToIgnoreCase
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-15
  • 2015-10-27
  • 2016-10-14
  • 2013-08-28
  • 2010-10-21
  • 2013-07-05
相关资源
最近更新 更多