如何在JAVA中对JSONArray进行排序

参见英文答案 > Android how to sort JSONArray of JSONObjects6
如何按对象的字段排序对象的JSONArray?

输入:

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

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

[
    { "ID": "432","Name": "Dilip Singh" }
    { "ID": "135",];

解决方法

尝试这个:
//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对象中.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...