如何排序的Java JSON对象数组 [英] How to sort array of json objects in java
本文介绍了如何排序的Java JSON对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在jsonarray 2 JSON对象,像这样
i have two json objects in jsonarray like this
"errorCode": "1",
"data": [
{
"messageId": 590,
"message": "WvZiT3RPm7feC6Hxsa/Ing==",
"messageType": "CHAT",
"sentOn": "01:51 PM, Apr 06, 2013",
"mainParent": 589,
"officeId": "19",
"webParent": 590
},
{
"messageId": 589,
"message": "1A45rtoC3Cy88h73TEvDqQ==",
"messageType": "CHAT",
"sentOn": "01:50 PM, Apr 06, 2013",
"parent": 0,
"signImg": null,
"mainParent": 589,
"officeId": "19",
"webParent": 1
}
]
所以我要在基于消息的ID键升序排列。我试着用用比较的对象类型为JSON对象,我收到错误的compareTo方法。请建议我
so i want to sort in ascending order based on message id key. i tried with comparator with object type as json object, i am getting error in compareto method. please suggest me
推荐答案
我张贴的答案在这里帮助别人谁所面临的问题,这类问题。
I am posting the answer here helping others who are facing the issue with this kind of problems.
public static JSONArray getSortedList(JSONArray array) throws JSONException {
List<JSONObject> list = new ArrayList<JSONObject>();
for (int i = 0; i < array.length(); i++) {
list.add(array.getJSONObject(i));
}
Collections.sort(list, new SortBasedOnMessageId());
JSONArray resultArray = new JSONArray(list);
return resultArray;
}
的code这部分将有助于JSON数组排序
This part of the code will help to sort the json array
退房SortBasedOnMessageId类下面。
Check out the SortBasedOnMessageId class below.
public class SortBasedOnMessageId implements Comparator<JSONObject> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
* lhs- 1st message in the form of json object. rhs- 2nd message in the form
* of json object.
*/
@Override
public int compare(JSONObject lhs, JSONObject rhs) {
try {
return lhs.getInt("messageId") > rhs.getInt("messageId") ? 1 : (lhs
.getInt("messageId") < rhs.getInt("messageId") ? -1 : 0);
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
这篇关于如何排序的Java JSON对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文