转:Android--JSONArray排序 - 掌缘生灭

1、先把JSONArray放在一个ArrayList里边,利用ArrayList排序

JSONArray mJSONArray;

protected void sortJsonArrayByDate(String dateName){
    List list = new ArrayList ();
    JSONObject jsonObj = null;
    for (int i = 0; i < mJSONArray.length(); i++) {
        jsonObj = mJSONArray.optJSONObject(i);
        list.add(jsonObj);
    }
    //排序操作
    JsonComparator pComparator =  new JsonComparator(dateName);
    Collections.sort(list, pComparator);
    
    //把数据放回去 
   mJSONArray = new JSONArray();
    for (int i = 0; i < list.size(); i++) {
        jsonObj = list.get(i);
        mJSONArray.put(jsonObj);
    }
}

2、实现 Comparator 接口,自定义比较规则

public class JsonComparator implements Comparator<JSONObject>{
  
  String dateName = "";
  JsonComparator(String dateName){
    this.dateName = dateName;
  }
  @Override
  public int compare(JSONObject json1, JSONObject json2){
    String date1 = json1.optString(dateName);
    String date2 = json2.optString(dateName);
    if(date1.compareTo(date2) < 0){
      return 1;
    }else if(date1.compareTo(date2) >0){
      return -1;
    }
    return 0;
  }
}

你可能感兴趣的:(Andriod)