How to sort JSONArray of JSONObject which contain another JSONObject?

I am able to sort JSONArray of JSONObject but I stuck when I need to sort array like follows:

[{
    "key1": "value1",
    "key2": "value2",
    "key3": {
        "key4": "value4",
        "key5": "value5"
    }
}, {
    "key1": "value1",
    "key2": "value2",
    "key3": {
        "key4": "value4",
        "key5": "value5"
    }
}]

I want to sort this array on "Key4".

Here is my code while sorting on key1

public static JSONArray sortJsonArray(JSONArray array, final String key) throws JSONException 
{
        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 = null;
                String rid = null;
                try {
                    lid = lhs.getString(key);
                    rid = rhs.getString(key);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // Here you could parse string id to integer and then compare.
                return lid.compareTo(rid);
            }
        });
        return new JSONArray(jsons);
    }

Upvotes: 0

Views: 957

Answers (2)

Just pasting my code Here(As per @cricket_007 Helps), May this help some others:

public static JSONArray sortJsonArrayOpenDate(JSONArray array) throws JSONException {
        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 = null;
                String rid = null;
                try {
                    lid = lhs.getJSONObject("key3").getString("key4");
                    rid = rhs.getJSONObject("key3").getString("key4");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return lid.compareTo(rid);
            }
        });
        return new JSONArray(jsons);
    }

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191738

Just compare lhs.getJSONObject("key3").getString("key4") to rhs.getJSONObject("key3").getString("key4").

Upvotes: 1

Related Questions