如何在JAVA中对JSONArray进行排序

37

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

输入:

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

期望输出(按“名称”字段排序):

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

我想按“名称”进行排序。输出应为: 432 Aaron Luke 252 Dilip Singh 135 Fargo Chan - kumarhimanshu449
1个回答

104

尝试这个:

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

1
感谢您的回答。帮了很大的忙。 - Manoj Fegde
1
谢谢你的回答。我最后不需要for循环。 - user3079872
我知道这个方法是可行的,但我们不得不采用这种方式来重复使用排序函数,尽管我们知道JsonArray将项作为集合private final List<JsonElement> elements包含在内,但它是私有的! - Christophe Roussy
1
好的答案,但这不会忽略大小写(A>B>C>a)。 - August
1
忘了为将来的我和其他人添加-只需更改为“compareToIgnoreCase”。 - August
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接