Jsonobject sorting in JsonArray,
Package com. run. horus. earlywaring. common;
Import java. util. ArrayList;
Import java. util. Collections;
Import java. util. Comparator;
Import java. util. List;
Import net. sf. json. JSONArray;
Import net. sf. json. JSONException;
Import net. sf. json. JSONObject;
Public class SortJsonArray {
Public static JSONArray sortJsonArray (JSONArray array ){
JSONArray sortedJsonArray = new JSONArray ();
List <JSONObject> jsonValues = new ArrayList <JSONObject> ();
For (int I = 0; I <array. size (); I ++ ){
JsonValues. add (array. getJSONObject (I ));
}
Collections. sort (jsonValues, new Comparator <JSONObject> (){
// You can change "Name" with "ID" if you want to sort by ID
Private static final String KEY_NAME = "ID ";
@ Override
Public int compare (JSONObject a, JSONObject B ){
String valA = new String ();
String valB = new String ();
Try {
// Here is the business that a and B need to process. You need to modify it according to your rules.
String aStr = a. getString (KEY_NAME );
ValA = aStr. replaceAll ("-","");
String bStr = B. getString (KEY_NAME );
ValB = bStr. replaceAll ("-","");
} 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 <array. size (); I ++ ){
SortedJsonArray. add (jsonValues. get (I ));
}
Return sortedJsonArray;
}
}
Original article: http://www.mamicode.com/info-detail-2094873.html