How to Create a JSONArray in Java Using JSONObject

Question

How can I create a JSON object in Java that includes nested JSONArrays using JSONObject?

{"employees": [{"firstName": "John", "lastName": "Doe"}, {"firstName": "Anna", "lastName": "Smith"}, {"firstName": "Peter", "lastName": "Jones"}], "manager": [{"firstName": "John", "lastName": "Doe"}, {"firstName": "Anna", "lastName": "Smith"}, {"firstName": "Peter", "lastName": "Jones"}]}

Answer

Creating a structured JSON representation in Java involves using the `JSONObject` and `JSONArray` classes from the JSON library. In this guide, we will walk through how to construct a JSON object that contains arrays of employee and manager information.

import org.json.JSONArray;
import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        // Create JSON Arrays for employees and managers
        JSONArray employees = new JSONArray();
        JSONArray managers = new JSONArray();

        // Adding employee details
        employees.put(new JSONObject().put("firstName", "John").put("lastName", "Doe"));
        employees.put(new JSONObject().put("firstName", "Anna").put("lastName", "Smith"));
        employees.put(new JSONObject().put("firstName", "Peter").put("lastName", "Jones"));

        // Adding manager details
        managers.put(new JSONObject().put("firstName", "John").put("lastName", "Doe"));
        managers.put(new JSONObject().put("firstName", "Anna").put("lastName", "Smith"));
        managers.put(new JSONObject().put("firstName", "Peter").put("lastName", "Jones"));

        // Creating the final main JSON object
        JSONObject mainObject = new JSONObject();
        mainObject.put("employees", employees);
        mainObject.put("manager", managers);

        // Printing the final JSON structure
        System.out.println(mainObject.toString(4)); // Indented for readability
    }
}

Causes

  • Understanding the correct structure for nested JSON data.
  • Knowing how to utilize `JSONArray` and `JSONObject` classes effectively.

Solutions

  • Instantiate the `JSONObject` for the entire object.
  • Create `JSONArray` instances for employees and managers.
  • Add individual employee or manager `JSONObject`s to their respective `JSONArray`.

Common Mistakes

Mistake: Not importing necessary JSON library classes.

Solution: Ensure you have included the JSON library in your project, such as org.json.

Mistake: Directly trying to add simple Strings to JSONArray without using JSONObject.

Solution: Wrap simple key-value pairs inside a JSONObject before adding them to a JSONArray.

Helpers

  • JSONArray in Java
  • JSONObject in Java
  • Java JSON creation
  • Create JSON object Java
  • Java JSON example

Related Questions

⦿How to Load a Properties File Located Outside a JAR File in Java?

Learn how to access and load a properties file from the same directory as your Java JAR file without using commandline arguments.

⦿How to Return a JSON Object in a Spring Boot RestController

Learn how to properly return a JSON object in Spring Boot RestController and troubleshoot common issues.

⦿How Do Synchronized Static Methods Work in Java: Do They Lock on the Class or Object?

Learn how synchronized static methods in Java function. Understand if they lock on the class or the object along with tips on usage and common mistakes.

⦿How to Fix Java SecurityException: Signer Information Does Not Match

Learn how to resolve the Java SecurityException related to signer information mismatch in your classes. Detailed explanation and solutions included.

⦿How to Resolve JAXB IllegalAnnotations Exception Regarding Duplicate Property Names in Java

Learn how to fix JAXB IllegalAnnotationsException related to duplicate property names in your Java classes and ensure proper XML data handling.

⦿What is the Purpose of package-info.java in Java Projects?

Discover the role of packageinfo.java in Java projects its importance and whether you really need it. Learn more about package documentation practices.

⦿How to Retrieve Thread ID from a Thread Pool in Java?

Learn how to retrieve the thread ID from a fixed thread pool in Java when executing tasks. Discover a detailed explanation and sample code.

⦿How to Add a Maven Dependency in Eclipse: A Step-by-Step Guide

Learn how to add Maven dependencies in Eclipse even if youre just starting. Follow our stepbystep guide with expert tips and code snippets.

⦿Why Should You Use '==' Instead of '.equals()' for Null Checks in Java?

Discover why using for null checks in Java is preferred over .equals and learn best practices to avoid NullPointerExceptions.

⦿What are the Advantages of Using Scala/Lift Compared to Java/Spring?

Explore the key benefits of using ScalaLift over JavaSpring for web development including performance coding efficiency and functional programming features.

© Copyright 2025 - CodingTechRoom.com