0

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;


     }
1
  • upon which field do you want to sort? Commented Sep 2, 2014 at 15:07

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.