Tuesday, January 31, 2017

How to sort JSONArray in Android?

 /**  
  *   
  * @param jsonArr = Input your json array  
  * @param sortBy = column name which needs to sort  
  * @return required sorted jsonarray   
  */  
 public static JSONArray sortArray(JSONArray jsonArr, final String sortBy) {  
  JSONArray sortedJsonArray = new JSONArray();  
  try {  
  List < JSONObject > jsonValues = new ArrayList < JSONObject > ();  
  for (int i = 0; i < jsonArr.length(); i++) {  
   jsonValues.add(jsonArr.getJSONObject(i));  
  }  
  Collections.sort(jsonValues, new Comparator < JSONObject > () {  
   @Override  
   public int compare(JSONObject a, JSONObject b) {  
   String valA = new String();  
   String valB = new String();  
   try {  
    valA = (String) a.get(sortBy);  
    valB = (String) b.get(sortBy);  
   } catch (JSONException e) {  
    //do something  
   }  
   return valA.compareTo(valB);  
   //if you want to change the sort order, simply use the following:  
   //return -valA.compareTo(valB);  
   }  
  });  
  for (int i = 0; i < jsonArr.length(); i++) {  
   sortedJsonArray.put(jsonValues.get(i));  
  }  
  } catch (JSONException e) {  
  e.printStackTrace();  
  }  
  return sortedJsonArray;  
 }  

No comments :

Post a Comment