How to sort array of json objects in java

前端 未结 1 1089
难免孤独
难免孤独 2021-01-03 14:47

i have two json objects in jsonarray like this

\"errorCode\": \"1\",
\"data\": [
    {
        \"messageId\": 590,
        \"message\": \"WvZiT3RPm7feC6Hxsa/         


        
相关标签:
1条回答
  • 2021-01-03 15:29

    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;
    }
    

    This part of the code will help to sort the json array

    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;
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题