0

I have a webservice and I get this response when I call the webservice.

[
    {
        "ProjectID": 1,
        "SLNO": 1,
        "ID": 1,
        "Type": "Text",
        "Name": "First Name",
        "**Order**": 1,
        "Flag": "F"
    },
    {
        "ProjectID": 1,
        "SLNO": 3,
        "ID": 2,
        "Type": "Text",
        "Name": "Company",
        "**Order**": 5,
        "Flag": "F"
    },
    {
        "ProjectID": 1,
        "SLNO": 4,
        "ID": 4,
        "Type": "Text",
        "Name": "Personal Email",
        "**Order**": 3,
        "Flag": "F"
    },
    {
        "ProjectID": 1,
        "SLNO": 2,
        "ID": 8,
        "Type": "Text",
        "Name": "Last Name",
        "**Order**": 2,
        "Flag": "F"
    }
]

Now I want to sort this complete array depending on the order which I get inside this array? How can I achieve this?

user2699728
  • 377
  • 2
  • 8
  • 25

2 Answers2

1
array = JSONUtil.sort(array, new Comparator(){
               public int compare(Object a, Object b){
                  JSONObject    ja = (JSONObject)a;
                  JSONObject    jb = (JSONObject)b;
                  return Integer.valueOf(ja.getString("**Order**")).compareTo(Integer.valueOf(jb.getString("**Order**")));
               }
            });
Digvesh Patel
  • 6,503
  • 1
  • 20
  • 34
0

First of all, add these data in list like an ArrayList or HashMap. Then use the below code to sort your list data based on order.

class HashMapComparator implements Comparator<HashMap<String, String>> {
        private final String key;

        public HashMapComparator(String key) {
            this.key = key;
        }

        @Override
        public int compare(HashMap<String, String> lhs,
                HashMap<String, String> rhs) {
            String firstValue = lhs.get(key);
            String secondValue = rhs.get(key);
            return firstValue.compareTo(secondValue);
        }
    }

and call it as:

 Collections.sort(yourlistDTO, new HashMapComparator("order"));
Alberto Solano
  • 7,972
  • 3
  • 38
  • 61
Vijju
  • 3,458
  • 1
  • 22
  • 20