iamlukeyb
iamlukeyb

Reputation: 6557

Sort an Array of JSONObjects in a JSONArray Alphabetically

Hi I'm trying to sort a JSONArray of JSONObjects alphabetically but it seems to add in backslashes as it turns it into one big string. Does anyone know how to do arrange a JSONArray of JSONObjects Alphabetically?

I have tried converting the JSONArray to arraylist but it becomes an JSONArray of Strings that are in alphabetical order rather than JSONObjects

public static JSONArray sortJSONArrayAlphabetically(JSONArray jArray) throws JSONException{

         ArrayList<String> arrayForSorting = new ArrayList<String>();     

            if (jArray != null) { 
               for (int i=0;i<jArray.length();i++){ 
                   //FIND OUT COUNT OF JARRAY
                   arrayForSorting.add(jArray.get(i).toString());
               } 

              Collections.sort(arrayForSorting); 
              jArray = new JSONArray(arrayForSorting);

            } 


         return jArray;


     }

Upvotes: 0

Views: 2463

Answers (1)

HRold
HRold

Reputation: 229

Maybe something like this?

public static JSONArray sortJSONArrayAlphabetically(JSONArray jArray) throws JSONException
{
    if (jArray != null) {
        // Sort:
        ArrayList<String> arrayForSorting = new ArrayList<String>();
        for (int i = 0; i < jArray.length(); i++) {
            arrayForSorting.add(jArray.get(i).toString());
        } 
        Collections.sort(arrayForSorting);

        // Prepare and send result:
        JSONArray resultArray = new JSONArray();
        for (int i = 0; i < arrayForSorting.length(); i++) {
            resultArray.put(new JSONObject(arrayForSorting.get(i)));
        }
        return resultArray;
    }
    return null; // Return error.
 }

The function's caller can free the JSONArray and JSONObject elements when he no longer needs them.


Also, if you just want to sort a JSONArray, you can look here:
Sort JSON alphabetically

and eventually here:
Simple function to sort an array of objects

Upvotes: 2

Related Questions