Here is some code using java 6 to get you started:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();
Answer from Grammin on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 21453203 › json-array-of-arrays
java - JSon array of arrays - Stack Overflow
{ "nome":"team1", "game":"game", "intarray":[1,2], "arrayofintarrays":{ "couple":[] }, ‌​"arrayofstringarrays":{ "mossearray":[] } } ... Team[] teams_loaded= null; try { Reader reader = new InputStreamReader(DexLoader.class.getClassLoader().getResourceAsStream("teams.tx‌​t")); Gson gson = new GsonBuilder().create(); JsonReader read = new JsonReader(reader); teams_loaded = gson.fromJson(read, Team[].class); } catch(Exception c) { c.printStackTrace(); } ... As an aside, wouldn't it be simplier to just write the Java code rather than the XSD and then generate the Java code from it?
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonArray.html
JsonArray (Java(TM) EE 7 Specification APIs)
JsonArray represents an immutable JSON array (an ordered sequence of zero or more values).
🌐
Mkyong
mkyong.com › home › java › how to parse json array using gson
How to parse JSON Array using Gson - Mkyong.com
May 17, 2024 - Review another sample JSON array of array… a bit scary structure. [ { "id": 1, "name": "a", "types": [ [ {"id": 1,"name": "a1"}, {"id": 2,"name": "a2"} ], [ {"id": 3,"name": "a3"} ] ] }, { "id": 2, "name": "b", "types": [ [ {"id": 1,"name": "b1"} ], [ {"id": 2,"name": "b2"} ] ] } ] To match it correctly, we can change the types to List<ItemType> types[]. ... package com.mkyong.json.gson.model; import java.util.Arrays; import java.util.List; public class Item { private int id; private String name; // change List<ItemType> type -> List<ItemType>[] type private List<ItemType>[] types; @Override
🌐
Javatpoint
javatpoint.com › json-array
JSON Array - javatpoint
JSON Array for beginners and professionals with examples of JSON with java, json array of string, json array of numbers, json array of booleans, json srray of objects, json multidimentional array. Learn JSON array example with object, array, schema, encode, decode, file, date etc.
Top answer
1 of 1
1

Here is an approach using Jackson (I used version 2.11.1).

An "item" here is defined as one of the id/value pairs in the source JSON - for example:

{
  "id": "b61ffb48-ffc7-4ae6-81a2-78b632892fda",
  "value": "[email protected]"
}

I split the task into 2 parts:

  1. Cut off the data when the required limit is reached, by deleting subsequent items.

  2. Clean up any resulting empty objects or arrays.

Here is my input test data (based on the data provided in the question):

    private static final String JSON = "{\n"
            + " \"emails\": [{\n"
            + "         \"emails\": [{\n"
            + "             \"email\": {\n"
            + "                 \"id\": \"ac9e95cf-3338-4094-b465-e0e1deca23c4\",\n"
            + "                 \"value\": \"[email protected]\"\n"
            + "             }\n"
            + "         }]\n"
            + "     },\n"
            + "     {\n"
            + "         \"email\": {\n"
            + "             \"id\": \"b61ffb48-ffc7-4ae6-81a2-78b632892fda\",\n"
            + "             \"value\": \"[email protected]\"\n"
            + "         }\n"
            + "     }\n"
            + " ],\n"
            + " \"lastName\": {\n"
            + "     \"id\": \"ffe19ece-819b-4680-8e0b-8566b34c973d\",\n"
            + "     \"value\": \"LastName\"\n"
            + " },\n"
            + " \"firstName\": {\n"
            + "     \"id\": \"4ed234f4-f679-40f3-b76b-41d9fdef7390\",\n"
            + "     \"value\": \"FirstName\"\n"
            + " }\n"
            + "}";

The code:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.Iterator;

public class JsonReducer {

    // get the first n "id/value" items:
    private final int limit = 2;
    // tracks how close we are to the cutoff limit:
    private int counter = 0;

    public void doParsing() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode json = mapper.readValue(JSON, JsonNode.class);
        
        // show the input JSON formatted, just for this demo:
        System.out.println(json.toPrettyString());

        // a copy of the original - we will use this when cleaning up:
        JsonNode prevJson = json.deepCopy();
        // remove unwanted items from the JSON
        json = reduce(json);

        // clean up empty nodes resulting from removals:
        while (!json.equals(prevJson)) {
            prevJson = json.deepCopy();
            json = stripEmpty(json);
        }

        System.out.println("---------------------------------");
        System.out.println(json.toPrettyString());
    }

    private JsonNode reduce(JsonNode json) {
        for (JsonNode node : json) {
            if (node.isObject()) {
                counter++;
                //System.out.println("obj " + counter + " - " + node.toString());
                if (counter > limit) {
                    ((ObjectNode) node).removeAll();
                } else {
                    reduce(node);
                }
            } else if (node.isArray()) {
                ArrayNode arrayNode = (ArrayNode) node;
                //System.out.println("array - " + arrayNode.toString());
                arrayNode.forEach((item) -> {
                    // assume each item is a JSON object - no arrays of arrays:
                    ObjectNode objectNode = (ObjectNode) item;
                    reduce(objectNode);
                });
            } //else if (node.isTextual()) {
            //System.out.println("text  - " + node.asText());
            //}
        }
        return json;
    }

    private JsonNode stripEmpty(JsonNode json) {
        Iterator<JsonNode> it = json.iterator();
        while (it.hasNext()) {
            JsonNode child = it.next();
            if (child.isContainerNode() && child.isEmpty()) {
                it.remove(); // remove empty arrays [], and objects {}
            } else {
                stripEmpty(child);
            }
        }
        return json;
    }

    private static final String JSON = ... // as shown above.

}

The reduce() method recursively iterates through the JSON, keeping track of the number of items collected - and then deletes any in excess of the required number.

However, this can leave empty [] arrays or {} objects in the JSON, so the stripEmpty() method handles that.

Because we are iterating sequentially through the JSON from top to bottom and from outer to inner, it's possible that we may need more than one pass of the stripEmpty() method. There may be a more efficient approach, which only needs one pass, but this is approach is at least straightforward.

Examples of the results:

For limit = 2:

{
  "emails" : [ {
    "emails" : [ {
      "email" : {
        "id" : "ac9e95cf-3338-4094-b465-e0e1deca23c4",
        "value" : "[email protected]"
      }
    } ]
  }, {
    "email" : {
      "id" : "b61ffb48-ffc7-4ae6-81a2-78b632892fda",
      "value" : "[email protected]"
    }
  } ]
}

For limit = 1:

{
  "emails" : [ {
    "emails" : [ {
      "email" : {
        "id" : "ac9e95cf-3338-4094-b465-e0e1deca23c4",
        "value" : "[email protected]"
      }
    } ]
  } ]
}

For limit = 0:

{ }

Additional Points:

Not Generic

The approach assumes there are never any arrays nested directly inside other arrays - so none of this: [ [ {...} ] ]. In other words, this is not a 100% generic parser, but does have some limitations in line with the sample data in the question.

Consider using POJOs

This solution does not define any POJO java objects into which the data is loaded - but it can often be easier to get what you want by doing that:

  • load (deserialize) the data into one or more POJOs.
  • remove unwanted data from the POJOs.
  • serialize the remaining data back to JSON.

If the example were any more complicated than the one in the question, I think I would favor doing this instead of manipulating only JsonNode data.

Update

Given the changes to the question, I think the best approach I can suggest is to parse each "item" (see definition above) into a POJO which would simply contain 3 fields:

String attribute;
String id;
String value;

The code to do this is as follows:

    private void traverse(JsonNode json) {
        Iterator<Map.Entry<String, JsonNode>> it = json.fields();
        while (it.hasNext()) {
            Map.Entry<String, JsonNode> entry = it.next();
            String name = entry.getKey();
            JsonNode node = entry.getValue();

            if (node.isArray()) {
                ArrayNode arrayNode = (ArrayNode) node;
                arrayNode.forEach((item) -> {
                    // assume each item is a JSON object - no arrays of arrays:
                    ObjectNode objectNode = (ObjectNode) item;
                    traverse(objectNode);
                });
            } else {
                String id = node.get("id").asText();
                String value = node.get("value").asText();
                
                System.out.println("attr : " + name);
                System.out.println("id   : " + id);
                System.out.println("value: " + value);
                System.out.println("---");
            }
        }
    }

Instead of the println() statements, you would create a new instance of the POJO and add it to an ArrayList.

Now you have a standard list containing all your data - and you can access items 1 - 100, then 101 - 200... and so on, as needed for the user interface.

You would need to convert that raw POJO data back to whatever format the UI needs/expects, of course.

Using the example JSON from the question, the above approach prints this:

attr : email
id   : ac9e95cf-3338-4094-b465-e0e1deca23c4
value: [email protected]
---
attr : email
id   : b61ffb48-ffc7-4ae6-81a2-78b632892fda
value: [email protected]
---
attr : lastName
id   : ffe19ece-819b-4680-8e0b-8566b34c973d
value: LastName
---
attr : firstName
id   : 4ed234f4-f679-40f3-b76b-41d9fdef7390
value: FirstName
🌐
ReqBin
reqbin.com › json › java › uzykkick › json-array-example
Java | What is JSON Array?
Unlike dictionaries, where you can get the value by its key, in a JSON array, the array elements can only be accessed by their index. The following is an example of a JSON array with numbers.
🌐
TutorialsPoint
tutorialspoint.com › how-to-read-parse-json-array-using-java
How to read/parse JSON array using Java?
The iterator() method of the JSONArray class returns an Iterator object, using which you can iterate through the contents of the current array. Iterator<String> iterator = jsonArray.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } Below is an example of a Java program that parses the above-created sample.json file, reads its contents, and displays them.
Find elsewhere
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONArray.html
JSONArray
This increases the array's length by one. ... value - An object value. The value should be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. ... JSONException - If the value is non-finite number. public JSONArray put(int index, boolean value) throws JSONException · Put or replace a boolean value in the JSONArray. If the index is greater than the length of the JSONArray, then null elements will be added as necessary to pad it out.
🌐
CodeUtility
blog.codeutility.io › programming › how-to-use-arrays-in-json-with-examples-in-code-5eeef2665f
How to use Arrays in JSON (With Examples in Code) | CodeUtility
September 26, 2025 - Manipulating JSON arrays in Java is essential when dealing with REST API responses, data storage, or configuration files. Since Java is a statically typed language, you’ll often need to map JSON data to POJOs (Plain Old Java Objects), or use flexible types like List and Map when the structure is dynamic.
🌐
Processing
processing.org › reference › jsonarray
JSONArray / Reference / Processing.org
String[] species = { "Capra hircus", "Panthera pardus", "Equus zebra" }; String[] names = { "Goat", "Leopard", "Zebra" }; JSONArray values; void setup() { values = new JSONArray(); for (int i = 0; i < species.length; i++) { JSONObject animal = new JSONObject(); animal.setInt("id", i); animal.setString("species", species[i]); animal.setString("name", names[i]); values.setJSONObject(i, animal); } saveJSONArray(values, "data/new.json"); } // Sketch saves the following to a file called "new.json": // [ // { // "id": 0, // "species": "Capra hircus", // "name": "Goat" // }, // { // "id": 1, // "species": "Panthera pardus", // "name": "Leopard" // }, // { // "id": 2, // "species": "Equus zebra", // "name": "Zebra" // } // ]
🌐
Medium
medium.com › @Mohd_Aamir_17 › mastering-json-in-java-a-comprehensive-guide-to-handling-json-objects-arrays-and-nodes-with-df57bf0ebff1
Mastering JSON in Java: A Comprehensive Guide to Handling JSON Objects, Arrays, and Nodes with Jackson | by Mohd Aamir | Medium
November 4, 2024 - Jackson’s ObjectMapper, JsonNode, ... on leveraging these classes to handle JSON efficiently. A JSON Object is a collection of key-value pairs, similar to a Map in Java....
🌐
JAXB
javaee.github.io › tutorial › jsonp001.html
Introduction to JSON
Objects are enclosed in braces ... be of any of the seven value types, including another object or an array. Arrays are enclosed in brackets ([]), and their values are separated by a comma (,)....
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Converting a JSON Object to a JSON Array in Java - Java Code Geeks
August 1, 2025 - 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.
🌐
LabEx
labex.io › tutorials › java-how-to-create-json-arrays-420797
How to create JSON arrays | LabEx
Learn efficient Java techniques for creating and manipulating JSON arrays with practical examples and methods for modern software development
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-json-array-object-to-java-object
How to Convert JSON Array Object to Java Object? - GeeksforGeeks
July 23, 2025 - For example, storing a list of items, user profiles, product catalog, etc. JSON arrays allow ordered access to the values using indices like in regular arrays in other languages (0 indexed). ... Iterating and parsing manually. Below are the steps and implementation to convert JSON Array object to Java object using Jackson library.
🌐
Android Developers
developer.android.com › api reference › jsonarray
JSONArray | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Javadoc.io
javadoc.io › doc › org.json › json › 20171018 › org › json › JSONArray.html
JSONArray (JSON in Java 20171018 API)
Latest version of org.json:json · https://javadoc.io/doc/org.json/json · Current version 20171018 · https://javadoc.io/doc/org.json/json/20171018 · package-list path (used for javadoc generation -link option) https://javadoc.io/doc/org.json/json/20171018/package-list ·
🌐
Baeldung
baeldung.com › home › java › java list › converting a java list to a json array
Converting a Java List to a Json Array | Baeldung
June 18, 2025 - Furthermore, web services and APIs often rely on JSON format to provide public data in a standardized manner. Its versatility makes it compatible with modern programming languages, allowing seamless integration across different platforms and technologies. In this scenario, let’s consider a Java list named “articles” that contains elements as follows: public List<String> list = Arrays.asList("Article 1", "Article 2", "Article 3"); public String expectedJsonArray = "[\"Article 1\",\"Article 2\",\"Article 3\"]";