
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort a JSONArray in Java
In this article, we will learn how to sort a JSON array in Java. But first, let's understand what JSON is. If you do not have knowledge about JSON, you can refer to the tutorial JSON Overview. Now, let's see different ways to sort a JSON array in Java.
Ways to sort a JSON array in Java
Following are different ways to sort a JSON array in Java -
- Sort JSON array Without any Dependency
- Using org.json library: Methods are getJSONArray() and getJSONObject()
- Using Gson library: Methods are JsonParser.parseString(json).getAsJsonArray()
- Using Jackson library: Methods are ObjectMapper.readTree(json)
Let's know them in detail one by one.
Sort JSON array Without any Dependency
Let's see how to sort a JSON array without any dependency. Steps to sort a JSON array without any dependency:
- Define a JSON-like array string.
- Parse the JSON array string into a list of maps.
- Sort the list by a specific key, for example, 'age'.
- Use a custom comparator to sort the list based on the 'age' key.
- Convert the list back to a JSON array string.
- Print the sorted JSON array.
Example
The following is the example code that sorts a JSON array without any dependency.
import java.util.*; public class SortJsonArrayManually { public static void main(String[] args) { // Step 1: Define a JSON-like array string String jsonArrayStr = "[{"name":"Alice","age":30},{"name":"Bob","age":22},{"name":"Charlie","age":25}]"; // Step 2: Parse JSON array string into a list of maps List<Map<String, Object>> parsedList = new ArrayList<>(); String trimmed = jsonArrayStr.substring(1, jsonArrayStr.length() - 1); // remove [ ] String[] jsonObjects = trimmed.split("(?<=\}),\{"); // split objects for (String objStr : jsonObjects) { objStr = objStr.replaceAll("[\{\}"]", ""); // remove braces and quotes String[] keyVals = objStr.split(","); Map<String, Object> map = new HashMap<>(); for (String pair : keyVals) { String[] entry = pair.split(":"); String key = entry[0].trim(); String value = entry[1].trim(); if (key.equals("age")) { map.put(key, Integer.parseInt(value)); } else { map.put(key, value); } } parsedList.add(map); } // Step 3: Sort the list by 'age' parsedList.sort(Comparator.comparingInt(entry -> (int) entry.get("age"))); // Step 4: Convert list back to JSON array string StringBuilder resultJson = new StringBuilder(); resultJson.append("["); for (int i = 0; i < parsedList.size(); i++) { Map<String, Object> item = parsedList.get(i); resultJson.append("{"); resultJson.append(""name":"").append(item.get("name")).append("","); resultJson.append(""age":").append(item.get("age")); resultJson.append("}"); if (i != parsedList.size() - 1) resultJson.append(","); } resultJson.append("]"); // Step 5: Print the sorted JSON array System.out.println(resultJson.toString()); } }
Following is the output of the above code:
[{"name":"Bob","age":22},{"name":"Charlie","age":25},{"name":"Alice","age":30}]
Sort JSON array using org.json library
The org.json is a common library that most Java developers use because it is simple and easy to use. Let's see how to sort a JSON array using the org.json library.
Before we start with coding, we need the org.json library. You can download the jar file from the following link:
- Download org.json
- Or you can add the dependency in your Maven project:
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20210307</version> </version>
Steps to sort a JSON Array Using org.json Library:
- Import the org.json library classes: JSONArray and JSONObject.
- Create a JSON array and populate it with JSON objects.
- Convert the JSONArray to a List of JSONObject.
- Sort the list using Collections.sort() and a custom comparator.
- Convert the sorted list back to a JSONArray.
- Print the sorted JSON array.
Example
The following is the example code that sorts a JSON array using the org.json library.
import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortJsonArrayWithLibrary { public static void main(String[] args) { // Step 1: Create a JSON array JSONArray originalArray = new JSONArray(); originalArray.put(new JSONObject() .put("name", "Zara") .put("age", 28)); originalArray.put(new JSONObject() .put("name", "Alex") .put("age", 22)); originalArray.put(new JSONObject() .put("name", "Mike") .put("age", 25)); // Step 2: Convert JSONArray to List<JSONObject> List<JSONObject> jsonList = new ArrayList<>(); for (int i = 0; i < originalArray.length(); i++) { jsonList.add(originalArray.getJSONObject(i)); } // Step 3: Sort the list by age (ascending) Collections.sort(jsonList, new Comparator<JSONObject>() { public int compare(JSONObject a, JSONObject b) { return Integer.compare(a.getInt("age"), b.getInt("age")); } }); // Step 4: Convert sorted list back to JSONArray JSONArray sortedArray = new JSONArray(); for (JSONObject obj : jsonList) { sortedArray.put(obj); } // Step 5: Print the sorted JSON array System.out.println(sortedArray.toString(2)); // pretty print with indentation } }
Following is the output of the above code:
[ { "name": "Alex", "age": 22 }, { "name": "Mike", "age": 25 }, { "name": "Zara", "age": 28 } ]
Sort JSON array using Gson library
Gson is a Java library that can be used to convert Java Objects into their JSON representation and vice versa. Gson is used for working with JSON in Java. It is developed by Google and mostly used in Android applications.
Before we start with coding, we need the Gson library. You can download the jar file from the following link:
- Download Gson
- Or you can add the dependency in your Maven project:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </version>
Steps to sort a JSON array using the Gson library:
- First, include the Gson library in your project.
- Create a JSON array and add some JSON objects to it.
- Change the JSON array into a list of JSON objects.
- Sort the list by the key you want, like "age" or "name".
- Turn the sorted list back into a JSON array.
- Finally, display the sorted JSON array.
Example
The following is the example code that sorts a JSON array using the Gson library.
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonElement; import com.google.gson.Gson; import java.util.*; public class SortJsonArrayWithGson { public static void main(String[] args) { // Step 1: Create a JsonArray JsonArray jsonArray = new JsonArray(); JsonObject obj1 = new JsonObject(); obj1.addProperty("name", "Zara"); obj1.addProperty("age", 28); JsonObject obj2 = new JsonObject(); obj2.addProperty("name", "Alex"); obj2.addProperty("age", 22); JsonObject obj3 = new JsonObject(); obj3.addProperty("name", "Mike"); obj3.addProperty("age", 25); jsonArray.add(obj1); jsonArray.add(obj2); jsonArray.add(obj3); // Step 2: Convert JsonArray to List<JsonObject> List<JsonObject> list = new ArrayList<>(); for (JsonElement element : jsonArray) { list.add(element.getAsJsonObject()); } // Step 3: Sort the list by age list.sort(Comparator.comparingInt(o -> o.get("age").getAsInt())); // Step 4: Convert back to JsonArray JsonArray sortedArray = new JsonArray(); for (JsonObject obj : list) { sortedArray.add(obj); } // Step 5: Print the sorted array Gson gson = new Gson(); System.out.println(gson.toJson(sortedArray)); } }
Following is the output of the above code:
[{"name":"Alex","age":22},{"name":"Mike","age":25},{"name":"Zara","age":28}]
Sort JSON array using the Jackson library
Jackson is a library that processes JSON data. It is mainly used for converting Java objects to JSON and vice versa. Let's add the Jackson library to our project.
- Download the Jackson library from the following link:
- Download Jackson
- Or you can add the dependency in your Maven project:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.0</version> </dependency>
Steps to sort a JSON array using the Jackson library:
- First, include the Jackson library in your project.
- Create a JSON array and add some JSON objects to it.
- Change the JSON array into a list of JSON objects.
- Sort the list by the key you want, like "age" or "name".
- Turn the sorted list back into a JSON array.
- Finally, display the sorted JSON array.
Example
The Following is the example code that sorts a JSON array using the Jackson library.
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.JsonNode; import java.util.*; public class SortJsonArrayWithJackson { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); // Step 1: Create JSON Array ArrayNode jsonArray = mapper.createArrayNode(); ObjectNode obj1 = mapper.createObjectNode(); obj1.put("name", "Zara"); obj1.put("age", 28); ObjectNode obj2 = mapper.createObjectNode(); obj2.put("name", "Alex"); obj2.put("age", 22); ObjectNode obj3 = mapper.createObjectNode(); obj3.put("name", "Mike"); obj3.put("age", 25); jsonArray.add(obj1); jsonArray.add(obj2); jsonArray.add(obj3); // Step 2: Convert ArrayNode to List<ObjectNode> List<ObjectNode> list = new ArrayList<>(); for (JsonNode node : jsonArray) { list.add((ObjectNode) node); } // Step 3: Sort the list by age list.sort(Comparator.comparingInt(o -> o.get("age").asInt())); // Step 4: Convert back to ArrayNode ArrayNode sortedArray = mapper.createArrayNode(); for (ObjectNode obj : list) { sortedArray.add(obj); } // Step 5: Print the sorted array String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(sortedArray); System.out.println(result); } }
Following is the output of the above code:
[ { "name" : "Alex", "age" : 22 }, { "name" : "Mike", "age" : 25 }, { "name" : "Zara", "age" : 28 } ]