2013-04-06 83 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