How to sort GSON Array based on a key?

how to sort json array in java
sort json array by key
how to sort array of json objects in java
sort json array in android
sort jsonnode java
gson byte array
gson jsonarray to string
gson jsonarray stream

Consider the following is my Array


Created a JsonArray out of it, like following code does:

//Create a JSON Parser using GSON library 
objJsonParser = new JsonParser();
String strArrayText = [{"id":9,"name":"name9","valid":true}, ...]
JsonArray jsonArrayOfJsonObjects = objJsonParser.parse(strArrayText).getAsJsonArray();

Now, I am trying to sort jsonArrayOfJsonObjects based on name field.

Desired Output:


Could anyone help to sort this out with best apporach with respect to Java & Gson? Your inputs are greatly appreciated.

First of all, the proper way to parse your JSON is to create a class to encapsulate your data, such as:

public class MyClass {
    private Integer id;
    private String name;
    private Boolean valid;
    //getters & setters

And then:

Type listType = new TypeToken<List<MyClass>>() {}.getType();
List<MyClass> myList = new Gson().fromJson(strArrayText, listType);

Now you have a List and you want to sort it by the value of the attribute id, so you can use Collections as explained here:

public class MyComparator implements Comparator<MyClass> {
    public int compare(MyClass o1, MyClass o2) {
        return o1.getId().compareTo(o2.getId());

And finally:

Collections.sort(myList, new MyComparator());

Sorting a JSON Array in Java – Adeel's Corner, JSONObject's. So a json array of json objects, which is pretty common. Say you want to sort the JSONObjects in the JSONArray, based on a key  The above sort method would sort the array without any issues as it is an array of string elements. JSON return type is an array of objects. Hence sort method cannot be used directly to sort the array. However we can use a comparer function as the argument of the ‘sort’ method to get the sorting implemented.

Try this library method as a simple JSON-level alternative to model classes creation:

 * Sort JSON-array by a given key name (numbers or text expected).
 * @param jsonArray     JSON-array to sort.
 * @param keyNameToSort Key name to sort by. Expected are integer type 
 *                      (sorted ascending) or string type (sorted 
 *                      alphabetically).
public static JsonArray
  JsonArray jsonArray,
  String keyNameToSort) {

  JsonArray sortedJsonArray = new JsonArray();
  JsonObject jsonObject = null;
  int jsonElementIndex;
  TreeMap<Integer, JsonObject> integerSortedObjects = new TreeMap<>();
  TreeMap<String, JsonObject> stringSortedObjects = new TreeMap<>();

  for (
    jsonElementIndex = 0;
    jsonElementIndex < jsonArray.size();
    jsonElementIndex++) {

    try {

      // A JSON-Object from JSON-array:

      jsonObject =

    } catch (Exception notAnObject) {

    for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {

      // Look for the given key in the JSON-object:

      if (
        .equals(keyNameToSort)) {

        try {

          // If key is of integer type:


        } catch (Exception notAnInt) {

          try {

            // If key is of string type:


          } catch (Exception neitherIntNorString) {

  // Add sorted by number values first:

  for (Integer key : integerSortedObjects.keySet()) {


  // Add sorted by string values second:

  for (String key : stringSortedObjects.keySet()) {


  return sortedJsonArray;

Sorting a JSONArray by one of its values, I have a JSONArray which saves “Name” and “Best”. Best is always an int. I would like to be able to sort the array descending. I can not provide any code as  By writing a small callback function,  array of JSON data can be easily sorted. In this example, we use the JSON array that has name and sore. We will sort this date first by score in a descending order and then alphabetical order by name if two people have the same score.

you can use Gson library to get the Array(the class should implement comparable) and sort with arrays.sort();


How can we sort a JSONArray in Java?, A JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface. We can sort a JSONArray in the  So a json array of json objects, which is pretty common. Say you want to sort the JSONObjects in the JSONArray, based on a key in the JSONObject. Let’s start by converting a JSONArray to a Collection of JSONObjects, using the java List type:

Sortable JsonArray, java -cp .:gson-2.1.jar IterableJsonArray '["foo","bar","baz"]' foo bar baz. Unfortunately, there's no easy way to sort a JsonArray in place. There To sort an array of objects by some key alphabetically in descending order, you only need to add as prefix a - (minus) symbol at the beginning of the key string, so the sort function will sort in descending order:

Gson, After reviewing the basics of Gson, model annotations and mapping of nested objects, we'll go on to a core feature: mapping of Arrays and Lists. Mapping of Null Values · Automatically Generate POJO Classes from JSON  When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. If the result is negative a is sorted before b. If the result is positive b is sorted before a. If the result is 0 no changes are done with the sort order of the two values.

Java Code Examples, This page provides Java code examples for addProperty("​action", action); JsonArray pr = new JsonArray(); for (String key : params.keySet())​  Olayinka and James show you how to dynamically sort an array of objects in JavaScript, using Array.prototype.sort() and a custom compare function. Get 3 months access to 400+ books and courses for

  • possible duplicate of Android how to sort JSONArray of JSONObjects
  • @MattBall JsonArray is very specifically not a Collection to avoid having to do lots of object translations unnecessarily.
  • @chrylis sorting a list and then serializing it to JSON should produce the desired output, if I understand the question correctly. Perhaps the OP really just wants a sorted JSONArray, but I read it as asking for sorted JSON.
  • You could also use an array and Java 8 lambdas: MyClass[] objects = new Gson().fromJson(strArrayText, MyClass[].class); Arrays.sort(objects, (MyClass m1, MyClass m2) -> m1.getId().compareTo(m2.getId()));
  • can you provide an example?
  • You have the example in the answer, If I have to code it, the code would be same.