Converting a JSON Object to a JSON Array in Java
This article explores various ways to perform Java JSON Object to Array conversion using popular libraries. Let us delve into understanding how to handle Java JSON Object Array conversion through multiple practical code examples and highlight key considerations along the way.
1. Introduction
JSON (JavaScript Object Notation) is widely used for data exchange between clients and servers. In Java, working with JSON data is common when dealing with REST APIs, configuration files, or message payloads. A JSON Object is a collection of key-value pairs, whereas a JSON Array is an ordered list of values. There are scenarios where we may need to convert a JSON Object into a JSON Array for easier iteration, standardization, or compatibility with downstream systems.
2. Why Converting?
Converting a JSON Object to a JSON Array can be useful in multiple scenarios, especially when working with structured data transformations:
- Preparing normalized data for frontend frameworks that iterate over arrays
- Transforming key-value pairs into list elements for easier processing
- Aligning with API specifications or schemas that expect array-based structures
However, before performing the conversion, it’s important to consider the following factors:
- If the original object keys carry meaningful information, they may be lost during conversion (especially in value-only arrays)
- Determine whether the result should be an array of objects, an array of values, or a custom structure
- Be mindful of element ordering, as JSON objects do not guarantee key order
3. Conversion Code Example
3.1 Using org.json Library
You can use the org.json library, which offers straightforward APIs for working with JSON data in Java. Let’s explore its usage through a practical example.
3.1.1 Convert JSON Object to Array of Values
// JsonConversionExample.java
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonConversionExample {
public static void main(String[] args) {
String jsonString = "{ \"apple\": 1, \"banana\": 2, \"cherry\": 3 }";
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = new JSONArray(jsonObject.toMap().values());
System.out.println("Converted JSON Array:");
System.out.println(jsonArray.toString(2));
}
}
3.1.1.1 Code Explanation and Output
In this Java code, we start by importing the necessary classes from the org.json package. The main method defines a JSON string representing a simple object with key-value pairs for fruits and their quantities. This string is parsed into a JSONObject instance. To convert this object into a JSON array, the code first transforms the JSONObject into a Map using toMap(), then extracts only the values from that map using values(), and wraps those values in a new JSONArray. The result is an array containing just the values [1, 2, 3], discarding the original keys. Finally, the array is printed in a nicely formatted (indented) JSON string using toString(2). When this code is executed, it produces the following output in the IDE console:
Converted JSON Array: [ 1, 2, 3 ]
3.1.2 Convert JSON Object to Array of Key-Value JSON Objects
// JsonObjectToArrayExample.java
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonObjectToArrayExample {
public static void main(String[] args) {
String jsonString = "{ \"apple\": 1, \"banana\": 2, \"cherry\": 3 }";
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray resultArray = new JSONArray();
for (String key : jsonObject.keySet()) {
JSONObject kvPair = new JSONObject();
kvPair.put("key", key);
kvPair.put("value", jsonObject.get(key));
resultArray.put(kvPair);
}
System.out.println("Key-Value Pair JSON Array:");
System.out.println(resultArray.toString(2));
}
}
3.1.2.1 Code Explanation and Output
This Java code demonstrates how to convert a JSON object into a JSON array of key-value pair objects using the org.json library. It begins by defining a JSON string containing fruit names as keys and their quantities as values. This string is parsed into a JSONObject. A new JSONArray named resultArray is initialized to store the transformed data. The program iterates over each key in the JSONObject using keySet(), and for every key, it creates a new JSONObject representing a key-value pair by inserting the key under the field "key" and the corresponding value under the field "value". Each key-value pair object is then added to the resultArray. Finally, the program prints the resulting array in a formatted JSON structure using toString(2), which outputs the array in a readable, indented format. When this code is executed, it produces the following output in the IDE console:
Key-Value Pair JSON Array:
[
{
"key": "apple",
"value": 1
},
{
"key": "banana",
"value": 2
},
{
"key": "cherry",
"value": 3
}
]
3.2 Using Jackson Library
Jackson is a widely adopted library for processing JSON in Java. Below is an example demonstrating how to convert a JSON object into a JSON array using Jackson.
// JacksonJsonConversion.java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Map;
public class JacksonJsonConversion {
public static void main(String[] args) throws Exception {
String jsonString = "{ \"red\": \"#FF0000\", \"green\": \"#00FF00\", \"blue\": \"#0000FF\" }";
ObjectMapper mapper = new ObjectMapper();
JsonNode objectNode = mapper.readTree(jsonString);
ArrayNode arrayNode = mapper.createArrayNode();
for (Iterator<Map.Entry<String, JsonNode>> it = objectNode.fields(); it.hasNext(); ) {
Map.Entry<String, JsonNode> entry = it.next();
ObjectNode node = mapper.createObjectNode();
node.put("key", entry.getKey());
node.set("value", entry.getValue());
arrayNode.add(node);
}
String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode);
System.out.println("Converted ArrayNode:");
System.out.println(result);
}
}
3.2.1 Code Explanation and Output
This Java code uses the Jackson library to convert a JSON object into an array of key-value pairs. It begins by defining a JSON string with color names as keys and their hex codes as values. An ObjectMapper is used to parse the JSON string into a JsonNode representing the object. A new ArrayNode is then created to hold the converted key-value structure. The code iterates through each entry in the original JsonNode using the fields() method. For each key-value pair, a new ObjectNode is created with two fields: "key" and "value", storing the original key and its corresponding value. These nodes are added to the ArrayNode. Finally, the resulting array is printed in a pretty-printed JSON format using writerWithDefaultPrettyPrinter().When this code is executed, it produces the following output in the IDE console:
Converted ArrayNode:
[
{
"key" : "red",
"value" : "#FF0000"
},
{
"key" : "green",
"value" : "#00FF00"
},
{
"key" : "blue",
"value" : "#0000FF"
}
]
3.3 Manual Conversion Using Java Collections
// ManualJsonConversion.java
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class ManualJsonConversion {
public static void main(String[] args) {
Map<String, Integer> fruitMap = new LinkedHashMap<>();
fruitMap.put("apple", 10);
fruitMap.put("banana", 20);
fruitMap.put("cherry", 30);
JsonArray array = new JsonArray();
for (Map.Entry<String, Integer> entry : fruitMap.entrySet()) {
JsonObject obj = new JsonObject();
obj.addProperty("key", entry.getKey());
obj.addProperty("value", entry.getValue());
array.add(obj);
}
Gson gson = new Gson();
System.out.println("Gson-based Array Output:");
System.out.println(gson.toJson(array));
}
}
3.3.1 Code Explanation and Output
This Java example demonstrates how to manually convert a Map to a JSON array using the Gson library. A LinkedHashMap is created to store fruit names as keys and their quantities as values. A new JsonArray is initialized to store the converted output. The code then iterates over each entry in the map using entrySet(). For every key-value pair, it creates a JsonObject with two properties: "key" and "value", representing the original map’s key and value. Each of these objects is added to the JsonArray. Finally, the array is serialized into a JSON string using a Gson instance and printed to the console.
Gson-based Array Output:
[
{
"key": "apple",
"value": 10
},
{
"key": "banana",
"value": 20
},
{
"key": "cherry",
"value": 30
}
]
4. Conclusion
Converting a JSON Object to a JSON Array in Java is a common requirement when working with dynamic JSON structures, APIs, or data transformations. Depending on your use case, you can use libraries like org.json, Jackson, or Gson for effective conversions. While org.json is lightweight, Jackson and Gson provide more flexibility and type safety. Always evaluate whether the keys in your original object matter, and pick the right structure for your downstream needs.

