2013-04-06 76 views
1

JSON对象数组我在jsonarray 2个JSON对象这样如何排序在Java

"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方法中的错误。请建议我

+0

你正试图做到这一点。在转换为JSON之前(如果你正在生成这个)或者在从JSON转换为java对象之后(因为你并没有将这一切全部保存为JSON,我相信 - 你将它解析为对象为了便于编码,有一点,对吧?)。做它的JSON是痛苦的。 – 2013-04-06 20:21:37

+0

@GabeSechan我读到这个问题的方式,我怀疑他正在使用JSON库并试图操纵JSON DOM。 @ user2014616请发布您的“比较器”代码和您遇到的错误。 – Barend 2013-04-06 20:25:38

+0

转换成JSON之前有没有什么办法来排序 – AndroidDev 2013-04-06 21:05:48

回答

6

我张贴的答案在这里帮助别人谁是这类问题所面临的问题。

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; 

    } 
} 
+0

你可以给SortBasedOnMessageId()实现吗?请朋友 – 2014-06-08 07:06:41

+0

@ShanXeeshi检查我更新的答案。如果它可以帮助你。接受答案 – AndroidDev 2014-06-09 06:43:34

+0

感谢答复,根据我的要求,它的工作原理让您更新的答案主意了很多有想法 – 2014-06-09 09:27:49