Hello Guys
Here, I am writing the code for sorting JSONArray in java technology.
we can sort jsonarray in ascending or in descending order according to our requirement by changing pattern as below.
private static final Pattern PATTERN = Pattern.compile("(\\D*)(\\d*)");
Following sortJson(jsonArray,String type) method sort the json array, in which we need to pass JSONArray object and key name(i.e String type) of JSONObject.
private static final Pattern PATTERN = Pattern.compile("(\\D*)(\\d*)");
public static JSONArray sortJson(JSONArray jsonArraylab,String type)
{
final String value=type;
JSONArray sortedJsonArray = JSONFactoryUtil.createJSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArraylab.length(); i++) {
jsonValues.add(jsonArraylab.getJSONObject(i));
}
Collections.sort( jsonValues, new Comparator<JSONObject>() {
//You can change "Name" with "ID" if you want to sort by ID
private final String KEY_NAME = value;
@Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
valA = (String) a.getString(KEY_NAME);
valB = (String) b.getString(KEY_NAME);
Matcher m1 = PATTERN.matcher(valA);
Matcher m2 = PATTERN.matcher(valB);
// The only way find() could fail is at the end of a string
while (m1.find() && m2.find()) {
// matcher.group(1) fetches any non-digits captured by the
// first parentheses in PATTERN.
int nonDigitCompare = m1.group(1).compareTo(m2.group(1));
if (0 != nonDigitCompare) {
return nonDigitCompare;
}
// matcher.group(2) fetches any digits captured by the
// second parentheses in PATTERN.
if (m1.group(2).isEmpty()) {
return m2.group(2).isEmpty() ? 0 : -1;
} else if (m2.group(2).isEmpty()) {
return +1;
}
BigInteger n1 = new BigInteger(m1.group(2));
BigInteger n2 = new BigInteger(m2.group(2));
int numberCompare = n1.compareTo(n2);
if (0 != numberCompare) {
return numberCompare;
}
}
// Handle if one string is a prefix of the other.
// Nothing comes before something.
return m1.hitEnd() && m2.hitEnd() ? 0 :m1.hitEnd()? -1 : +1;
}
});
for (int i = 0; i < jsonValues.size(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
return sortedJsonArray;
}
0 Comment(s)