Jsonobject sorting in JsonArray,

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.