Reputation: 10158
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 to users option(sorting by user_id tag in ascending or descending order). I have parsed the JSON as the following:
JSONObject mObject = new JSONObject(JSONResponse);
String commentsVal = mObject.getString("message");
String resultVal = mObject.getString("result");
JSONArray resultArray = new JSONArray(resultVal);
int resultSize = resultArray.length();
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultObj = resultArray.getJSONObject(i);
resultObj.getString("comment_id");
.....
}
..............
and this is my JSON response:
{
"success": 1,
"message": "some message",
"result": [
{
"comment_id": "43906",
"comp_id": "116725",
"user_id": "48322",
"agree": "0",
.....
"replies": [....]
},
{
"comment_id": "43905",
"comp_id": "116725",
"user_id": "48248",
"agree": "0",
.......
"replies": [...]
}
]
}
I need the "result" JSON Array sorted by the "user_id" tag name while parsing, how to do it in Android?
Upvotes: 1
Views: 12130
Reputation: 7450
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.
Upvotes: 17
Reputation: 26034
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;
}
}
Upvotes: 0
Reputation: 3408
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
Upvotes: 1