Android How to Sort JSONarray of JSONobjects

Android how to sort JSONArray of JSONObjects

The issue is that JSONArray more or less holds JSONObjects (and other JSONArrays) which ultimately are strings. Deserializing the strings entirely into POJOs, sorting those, then back into JSON is fairly heavy.

The second issue is that a JSONArray can contain: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object; i.e. it is mixed types, making it hard to just dump the elements into a List of some type and sort that, then pass through the list dumping sorted items back into the JSON array. the only certain way to get a common type of each element from the JSONArray is using the Object get() method.. of course then all you have is Object objects and won't be able to do any meaningful sorting on them without revisiting the serialization issue.

Assuming your JSONArray contains homogeneously structured values, you could iterate through the JSONArray, calling one of the typed get() methods on each one, dumping them into a List type, then sorting on that. If your JSONArray just holds "simple" type like String or numbers, this is relatively easy. This isn't exact code but something like:

List<String> jsonValues = new ArrayList<String>();
for (int i = 0; i < myJsonArray.length(); i++)
jsonValues.add(myJsonArray.getString(i));
Collections.sort(jsonValues);
JSONArray sortedJsonArray = new JSONArray(jsonValues);

Of course, if you have nested objects this can get a little trickier. If the value(s) you want to sort on live in the top level, it may not be soo bad...

List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < myJsonArray.length(); i++)
jsonValues.add(myJsonArray.getJSONObject(i));

Then use a comparator like this to sort:

class JSONComparator implements Comparator<JSONObject>
{

public int compare(JSONObject a, JSONObject b)
{
//valA and valB could be any simple type, such as number, string, whatever
String valA = a.get("keyOfValueToSortBy");
String valB = b.get("keyOfValueToSortBy");

return valA.compareTo(valB);
//if your value is numeric:
//if(valA > valB)
// return 1;
//if(valA < valB)
// return -1;
//return 0;
}
}

Again, this makes some assumptions about the homogeneity of the data in your JSONArray. Adjust to your case if possible. Also you will need to add your exception handling, etc. Happy coding!

edit
fixed based on comments

Java Android - How to sort a JSONArray based on keys

First parse your array in a list

JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}

then use collection.sort to sort the newly created list

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

public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();

try {
valA = (String) a.get("distance");
valB = (String) b.get("distance");
}
catch (JSONException e) {
//do something
}

return valA.compareTo(valB);
}
});

Insert the sorted values in your array

for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonList.get(i));
}

How to sort JSONArray in android

public static JSONArray sortJsonArray(JSONArray array) {
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 = lhs.getString("comment_id");
String rid = rhs.getString("comment_id");
// Here you could parse string id to integer and then compare.
return lid.compareTo(rid);
}
});
return new JSONArray(jsons);
}

This piece of code could return a sorted JSONArray, but i still recommend you to parse JSONObject to your own data beans, and then do the sorting on them.

How to Sort JSON Array from JSON Objects in Android?

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;
}
}
});

Is there any easy way to sort a JSONArray of objects by an attribute in Android?

Perhaps using the Google GSON library you can deserialise the array to a typed collection of objects, and then using Collections perform a sort.

Look at 6th line in on the following link.. Looks a bit messy but might be quickest way..

http://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples

Sort an Array of JSONObjects in a JSONArray Alphabetically

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

How to sort a jsonarray data by Date & Time and put in list view adapter

You should be able to use Collections.sort(...) passing in a Comparator that will compare 2 AppointmentInfoDto objects.

Collections.sort(listItemService, new Comparator<AppointmentInfoDto>() {

@Override public int compare(AppointmentInfoDto l, AppointmentInfoDto r) {
// Compare l.ScheduleOn and r.ScheduleOn
}

}


Related Topics



Leave a reply



Submit