android – 如何在java中对json对象的数组进行排序
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了android – 如何在java中对json对象的数组进行排序,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1464字,纯文字阅读大概需要3分钟。
内容图文
我在jsonarray中有两个json对象
"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方法中遇到错误.请建议我
解决方法:
我在这里发布答案,帮助那些面临这类问题的人.
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;
}
这部分代码将有助于对json数组进行排序
查看下面的SortBasedOnMessageId类.
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;
}
}
内容总结
以上是互联网集市为您收集整理的android – 如何在java中对json对象的数组进行排序全部内容,希望文章能够帮你解决android – 如何在java中对json对象的数组进行排序所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。