4

I have a JSON array, and I want to sort it Depending on the name and too alphabetically. My Json is as follows.

[
    {
        "UserID": 77,
        "InvID": 333,
        "Email": "sumeetssm@gmail.com",
        "Phone": "",
        "Name": "Summet",
        "Company": "",
        "Date": "2014-01-14T00:00:00"
    },
    {
        "UserID": 0,
        "InvID": 334,
        "Email": "amit@testt.com",
        "Phone": "",
        "Name": "Amit",
        "Company": "",
        "Date": "2014-01-14T00:00:00"
    },
    {
        "UserID": 3,
        "InvID": 335,
        "Email": "amitesh@yahoo.com",
        "Phone": "",
        "Name": "Amitesh",
        "Company": "",
        "Date": "2014-01-14T00:00:00"
    },
    {
        "UserID": 0,
        "InvID": 336,
        "Email": "foobar@test.com",
        "Phone": "",
        "Name": "FOO",
        "Company": "",
        "Date": "2014-01-14T00:00:00"
    },
    {
        "UserID": 0,
        "InvID": 337,
        "Email": "krazy.lance@gmail.com",
        "Phone": "",
        "Name": "Krazy",
        "Company": "",
        "Date": "2014-01-14T00:00:00"
    },
    {
        "UserID": 1,
        "InvID": 338,
        "Email": "test@yahoo.com",
        "Phone": "",
        "Name": "Test",
        "Company": "",
        "Date": "2014-01-14T00:00:00"
    },
    {
        "UserID": 0,
        "InvID": 339,
        "Email": "maktest@yahoo.com",
        "Phone": "",
        "Name": " ",
        "Company": "",
        "Date": "2014-01-14T00:00:00"
    },
    {
        "UserID": 0,
        "InvID": 340,
        "Email": "Sam@rediff.com",
        "Phone": "",
        "Name": "SAM",
        "Company": "",
        "Date": "2014-01-14T00:00:00"
    },
    {
        "UserID": 101,
        "InvID": 343,
        "Email": "anurag@yahoo.com",
        "Phone": "",
        "Name": "Anurag",
        "Company": "",
        "Date": "2014-01-14T00:00:00"
    },
    {
        "UserID": 95,
        "InvID": 379,
        "Email": "s@s.com",
        "Phone": "",
        "Name": "S",
        "Company": "",
        "Date": "2014-01-14T00:00:00"
    },
    {
        "UserID": 0,
        "InvID": 428,
        "Email": "sumeetssm@yahoo.com",
        "Phone": "",
        "Name": "Summet",
        "Company": "",
        "Date": "2014-01-16T00:00:00"
    },
    {
        "UserID": 4,
        "InvID": 494,
        "Email": "sameer@iconnectgroup.com",
        "Phone": "",
        "Name": "Sameer P",
        "Company": "",
        "Date": "2014-01-21T00:00:00"
    },
    {
        "UserID": 85,
        "InvID": 507,
        "Email": "jonny@dep.com",
        "Phone": "9404988188",
        "Name": "Jonny Dep",
        "Company": "Iconnect",
        "Date": "2014-01-22T00:00:00"
    }
]

As you can see I have a key value "Name" and in that I get respected names. I want to sort this Json array completely based on this names and that too alphabetically.Thanks in advance.

user2699728
  • 377
  • 2
  • 8
  • 25

5 Answers5

8

Convert JSONArray to Arraylist<JSONBbject> and use Collections to sort your arraylist

for example :

ArrayList<JSONObject> array = new ArrayList<JSONObject>();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
    try {
        array.add(jsonArray.getJSONObject(i));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Collections.sort(array, new Comparator<JSONObject>() {

    @Override
    public int compare(JSONObject lhs, JSONObject rhs) {
        // TODO Auto-generated method stub

        try {
            return (lhs.getString("Name").toLowerCase().compareTo(rhs.getString("Name").toLowerCase()));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }
});
henry4343
  • 3,871
  • 5
  • 22
  • 30
  • It is telling me to put it under try catch, and then it is asking me to add return type. Please help – user2699728 Jan 29 '14 at 07:04
  • If the code enter to the catch mean your json parse have a error, so that return 0 mean don't sort object – henry4343 Jan 29 '14 at 08:15
  • you should return outside the try..catch or change your function to return type to void, but this might not be desirable in for your purposes – Chris Apr 03 '14 at 10:05
  • please take a look at my [question](http://stackoverflow.com/questions/39952230/after-sorting-jsonarray-custom-list-view-not-changed) ..same issue – Manish Oct 10 '16 at 09:04
2

Firstly, parse the json data and add every json object to List of Object (e.g. Employee)

List<Employee> employees = parseJson(jsonDate);
Collections.sort(employees, new EmployeeComparator());

Here is the comparator implementation:

class EmployeeComparator implements Comparator<Employee> {
    @Override
    public int compare(Employee o1, Employee o2) {
        return o1.getName().compareTo(o2.getName());
    }
}
sudanix
  • 515
  • 3
  • 9
  • Can you please elaborate it a more, What exactly should be done in my case? – user2699728 Jan 29 '14 at 06:31
  • You have to parse json data. use JSONObject and JSONArray for that. also create a new class (Employee) to hold each item. Then iterate over all JSONArray items and add each one to a List of Employee. after that use Collection.sort() method to sort the list. – sudanix Jan 29 '14 at 06:45
  • I think this is a best answer of this question. – Viks Jun 08 '15 at 07:18
0
// try this way i have gave demo code you have modify as per your requirement.

public class MyActivity extends Activity {


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try{
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name","Haresh");
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("name","Akash");
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("name","Biraj");
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("name","Salim");
            JSONObject jsonObject4 = new JSONObject();
            jsonObject4.put("name","Saloni");
            jsonArray.put(jsonObject1);
            jsonArray.put(jsonObject);
            jsonArray.put(jsonObject3);
            jsonArray.put(jsonObject2);
            jsonArray.put(jsonObject4);


            ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>)toList(jsonArray);
            Collections.sort(list,new Comparator<HashMap<String, String>>() {
                @Override
                public int compare(HashMap<String, String> stringStringHashMap, HashMap<String, String> stringStringHashMap2) {
                    return stringStringHashMap.get("name").compareTo(stringStringHashMap2.get("name"));
                }
            });
            for (HashMap<String,String> row : list){
                System.out.println("Row :"+row.get("name"));
            }

        }catch (Exception e){
            e.printStackTrace();
        }


    }

    private Object fromJson(Object json) throws JSONException {
        if (json == JSONObject.NULL) {
            return null;
        } else if (json instanceof JSONObject) {
            return jsonToMap((JSONObject) json);
        } else if (json instanceof JSONArray) {
            return toList((JSONArray) json);
        } else {
            return json;
        }
    }

    public Map<String, String> jsonToMap(JSONObject object) throws JSONException {
        Map<String, String> map = new HashMap();
        Iterator keys = object.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            map.put(key, fromJson(object.get(key)).toString());
        }
        return map;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private List toList(JSONArray array) throws JSONException {
        List list = new ArrayList();
        int size = array.length();
        for (int i = 0; i < size; i++) {
            list.add(fromJson(array.get(i)));
        }
        return list;
    }


}
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
0

JSONArrays are not sortable. You can extract the data into an ArrayList and then sort with a comparator and then put back into the JSONArray.

Yushi
  • 416
  • 6
  • 24
0

On the Android side you generally won't sort objects in JSON format. If they do need to be sorted before you retrieve them, that is something that should occur on the backend.

Alternatively, and this is very common, you will parse the JSON objects into local Java objects (or Collections of objects), and then you can use a comparator to sort the collection based on a certain property that exists within all objects in the collection.

Fortunately both of these tasks have been asked and answered many times before. For more information on parsing JSON see How to parse JSON in Android. For more information on sorting objects in a collection see Android-java- How to sort a list of objects by a certain value within the object.

Community
  • 1
  • 1
Kyle Clegg
  • 38,547
  • 26
  • 130
  • 141