How to sort JSONArray by its Tag name with ascending and descending on android.
In my application i have a JSON like the following and need to display the data according
It seems to me like the easiest way to do it, rather than "sorting the JSON Array" as you suggest, is to just parse the whole thing into a data structure which contains the information like so:
class Results {
String user_id;
Strung comment_id;
}
Save this as an ArrayList or a [insert favourite List structure].
Once you've parsed the entire JSON Array, you can then sort your ArrayList based on the user_id field using Collections.sort
, giving you them in order
Following code may useful to you.
ArrayList<ResultBean> user_array;
Collections.sort(user_array, new Comparator<ResultBean>() {
@Override
public int compare(ResultBean data1, ResultBean data2) {
if (data1.getUserId() >= data2.getUserId()) {
return -1;
} else {
return 1;
}
}
});
Your ResultBean
will look like following.
public class ResultBean {
//other methods and declarations...
public int getUserId() {
return userId;
}
}
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.