我有一个web服务,当我调用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"
}
]
现在我想根据我在这个数组中的顺序对这个完整的数组进行排序?我怎样才能做到这一点?
答案 0 :(得分: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**")));
}
});
答案 1 :(得分:0)
首先,将这些数据添加到列表中,如ArrayList或HashMap。然后使用以下代码根据订单对列表数据进行排序。
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);
}
}
并将其命名为:
Collections.sort(yourlistDTO, new HashMapComparator("order"));