如何在java中对json对象的数组进行排序

时间:2013-04-06 20:16:15

标签: android json sorting

我在jsonarray中有两个像这样的json对象

"errorCode": "1",
"data": [
    {
        "messageId": 590,
        "message": "WvZiT3RPm7feC6Hxsa/Ing==",
        "messageType": "CHAT",
        "sentOn": "01:51 PM, Apr 06, 2013",

        "mainParent": 589,
        "officeId": "19",
        "webParent": 590
    },
    {
        "messageId": 589,
        "message": "1A45rtoC3Cy88h73TEvDqQ==",
        "messageType": "CHAT",
        "sentOn": "01:50 PM, Apr 06, 2013",

        "parent": 0,
        "signImg": null,
        "mainParent": 589,
        "officeId": "19",
        "webParent": 1
    }
]

所以我想根据消息ID键按升序排序。我尝试使用比较器,对象类型为json对象,我在compareto方法中遇到错误。请建议我

1 个答案:

答案 0 :(得分:6)

我在这里发布答案,帮助那些面临这类问题的人。

public static JSONArray getSortedList(JSONArray array) throws JSONException {
            List<JSONObject> list = new ArrayList<JSONObject>();
            for (int i = 0; i < array.length(); i++) {
                    list.add(array.getJSONObject(i));
            }
            Collections.sort(list, new SortBasedOnMessageId());

            JSONArray resultArray = new JSONArray(list);

            return resultArray;
}

这部分代码将有助于对json数组进行排序

查看下面的SortBasedOnMessageId类。

public class SortBasedOnMessageId implements Comparator<JSONObject> {
    /*
    * (non-Javadoc)
    * 
    * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
    * lhs- 1st message in the form of json object. rhs- 2nd message in the form
    * of json object.
    */
    @Override
    public int compare(JSONObject lhs, JSONObject rhs) {
        try {
            return lhs.getInt("messageId") > rhs.getInt("messageId") ? 1 : (lhs
                .getInt("messageId") < rhs.getInt("messageId") ? -1 : 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 0;

    }
}