1

如何在 Android 上按其标签名称升序和降序对 JSONArray 进行排序。

在我的应用程序中,我有一个如下所示的 JSON,需要根据用户选项显示数据(按 user_id 标签升序或降序排序)。我已将 JSON 解析如下:

JSONObject mObject = new JSONObject(JSONResponse);
String commentsVal = mObject.getString("message");
String resultVal = mObject.getString("result");
JSONArray resultArray = new JSONArray(resultVal);
int resultSize = resultArray.length();
for (int i = 0; i < resultArray.length(); i++) {
    JSONObject resultObj = resultArray.getJSONObject(i);
    resultObj.getString("comment_id");
    .....
}
..............  

这是我的 JSON 响应:

{
"success": 1,
"message": "some message",
"result": [
    {
        "comment_id": "43906",
        "comp_id": "116725",
        "user_id": "48322",
        "agree": "0",
        .....
        "replies": [....]
    },
    {
        "comment_id": "43905",
        "comp_id": "116725",
        "user_id": "48248",
        "agree": "0",
        .......
        "replies": [...]
    }
]

}

我在解析时需要按“user_id”标签名称排序的“结果”JSON 数组,如何在 Android 中完成?

4

3 回答 3

16
public static JSONArray sortJsonArray(JSONArray array) {
    List<JSONObject> jsons = new ArrayList<JSONObject>();
    for (int i = 0; i < array.length(); i++) {
        jsons.add(array.getJSONObject(i));
    }
    Collections.sort(jsons, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject lhs, JSONObject rhs) {
            String lid = lhs.getString("comment_id");
            String rid = rhs.getString("comment_id");
            // Here you could parse string id to integer and then compare.
            return lid.compareTo(rid);
        }
    });
    return new JSONArray(jsons);
}

这段代码可以返回一个已排序的 JSONArray,但我仍然建议您将 JSONObject 解析为您自己的数据 bean,然后对它们进行排序。

于 2013-07-17T11:10:32.170 回答
1

在我看来,最简单的方法是,而不是按照您的建议“对 JSON 数组进行排序”,而是将整个内容解析为包含如下信息的数据结构:

class Results {
     String user_id;
     Strung comment_id;
}

将其保存为 ArrayList 或 [插入收藏列表结构]。

一旦你解析了整个 JSON 数组,你就可以使用基于 user_id 字段对你的 ArrayList 进行排序Collections.sort,按顺序给你

于 2013-07-17T10:44:38.540 回答
0

以下代码可能对您有用。

ArrayList<ResultBean> user_array;
Collections.sort(user_array, new Comparator<ResultBean>() {
    @Override
    public int compare(ResultBean data1, ResultBean data2) {
        if (data1.getUserId() >= data2.getUserId()) {
            return -1;
        } else {
            return 1;
        }
    }
});

ResultBean将如下所示。

public class ResultBean {
    //other methods and declarations...
    public int getUserId() {
        return userId;
    }
}
于 2013-07-17T11:08:11.820 回答