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" },
];

推荐答案

Try this:

    //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对象中.

Json相关问答推荐

震击:三针并用震击

PowerShell:将Invoke-WebRequest与变量一起使用

我如何知道TJSONNumber是double还是double?

使用WSO2 JsonTransform Mediator对空值执行JsonExceptionUndeletedOperationException

419(未知状态)使用laravel处理PUT请求

震动范围改善

在 json 对象中存储多个键:值对

如何在 Apache NiFi 中使用 JoltTransformJson 删除流文件或具有空字段的整个对象?

在 JOLT 中重新排列值

使用 JQ 从文件中删除重复的 JSON 块

使用 jq 将键值行转换为 json

如何解决名为 null 的map值

如何让 JSON.NET 忽略对象关系?

如何在golang中获取 struct 的json字段名称?

在 Bash 中访问 JSON 对象 - 关联数组/列表/另一个模型

在 JSON 反序列化期间没有为System.String类型定义无参数构造函数

对象序列化为 JSON(使用 Gson).如何在 UpperCamelCase 中设置字段名称?

数据包含连续问号时无法理解的 jQuery $.ajax() 行为

ASP.NET MVC 读取原始 JSON 发布数据

如何使用 Javascript 将数据写入 JSON 文件