如何在JAVA中对JSONArray进行排序 [英] How can I sort a JSONArray in JAVA

查看:4995
本文介绍了如何在JAVA中对JSONArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to sort a JSONArray of objects by object's field?

输入:

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

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

Desired output (sorted by "Name" field):

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


推荐答案

试试这个:

    //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 object。

The sorted JSONArray is now stored in the sortedJsonArray object.

这篇关于如何在JAVA中对JSONArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆