Core Java

Fixing the JSONObject Begin With { Error in Java

JSON handling is a core part of modern Java applications, especially when working with REST APIs, configuration files, logging frameworks, or microservices. The org.json library is one of the simplest libraries for parsing JSON, but developers frequently encounter parsing errors when the input is malformed or unexpected. One of the most common issues is:

org.json.JSONException: JSONObject text must begin with '{'

Let us delve into evaluation of the Java JSONException, specifically the “JSONObject text must begin with curly brace” issue, to understand why it occurs and how to resolve it effectively.

1. Understanding the Error

A JSONObject in Java must always start with a curly brace ({). This is because { ... } represents an object in JSON notation. You will see this error when you pass a string to the new JSONObject(…) constructor and the string does NOT start with {. Some common incorrect formats include:

  • A JSON array (starting with [)
  • A plain string or number instead of JSON
  • HTML or error responses instead of JSON
  • Empty or null responses

For example, this triggers the error:

String input = "Hello";  // Not JSON
JSONObject obj = new JSONObject(input);  // ERROR

1.1 Common Scenarios That Trigger the Error

  • API response returns HTML instead of JSON: Sometimes backend services return an HTML error page (404, 500, etc.) instead of JSON. If you try to parse it directly as JSON, it will fail.
  • JSON Array passed instead of JSON Object: If the string starts with [, it’s a JSONArray, not a JSONObject.
  • Empty or null String: Parsing an empty string directly will also throw a JSONException.
  • JSON contains BOM (Byte Order Mark): Some files begin with invisible BOM characters, making the first character not {.
  • Incorrect serialization or encoding: If the backend sends encoded text, escaped JSON, or logs instead of actual JSON, parsing may fail.

2. Code Example: Safely parsing JSON and handling JSONException

This example demonstrates how to handle invalid JSON formats gracefully by detecting whether the input is a JSONObject or JSONArray before parsing.

// JsonParsingExample.java
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonParsingExample {

    public static void main(String[] args) {

        String response = "[{\"id\":101, \"name\":\"Alice\"}, {\"id\":102, \"name\":\"Bob\"}]";

        try {
            // Attempt to parse as JSONObject (WRONG)
            System.out.println("Trying to parse as JSONObject...");
            JSONObject obj = new JSONObject(response); // This will throw an exception

        } catch (JSONException e) {
            System.out.println("Caught Exception: " + e.getMessage());
            System.out.println("The input is not a JSONObject. Checking if it's a JSONArray...");

            // Try parsing as JSONArray
            try {
                JSONArray array = new JSONArray(response);
                System.out.println("Successfully parsed as JSONArray!");

                // Convert array item to JSONObject
                System.out.println("\nIterating through JSONArray:");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject item = array.getJSONObject(i);
                    System.out.println("ID: " + item.getInt("id") + ", Name: " + item.getString("name"));
                }

            } catch (JSONException ex) {
                System.out.println("Input is not valid JSON at all!");
            }
        }
    }
}

2.1 Code Explanation

The above Java code demonstrates how to safely parse JSON while handling potential parsing errors using the org.json library. It begins by defining a string named response that contains a valid JSON array with two objects, each representing a user with an id and name. Inside the main method, the code first attempts to parse this string as a JSONObject, even though the data actually starts with a [, indicating it is a JSONArray. Because a JSONObject must always begin with {, this incorrect attempt immediately triggers a JSONException. The program catches this exception in the first catch block and prints a message explaining that the input is not a valid JSONObject. It then proceeds to a secondary parsing attempt, this time correctly using new JSONArray(response), which successfully interprets the data as an array. After successful parsing, the code iterates through each element of the array using a for loop, retrieves each element as a JSONObject with getJSONObject(i), and then prints the values of the id and name fields using getInt() and getString(). If the second parsing attempt also fails—meaning the text is not valid JSON at all—the inner catch block handles this by printing an appropriate error message. Overall, the code shows how to detect whether JSON text is an object or an array, how to handle wrong assumptions gracefully, and how to extract structured data safely without crashing the application.

2.2 Code Output

Trying to parse as JSONObject...
Caught Exception: A JSONObject text must begin with '{' at 1 [character 2 line 1]
The input is not a JSONObject. Checking if it's a JSONArray...
Successfully parsed as JSONArray!

Iterating through JSONArray:
ID: 101, Name: Alice
ID: 102, Name: Bob

The output begins with the message “Trying to parse as JSONObject…” because the program first attempts to interpret the JSON string as a JSONObject. Since the input actually starts with a [, indicating it is a JSONArray, the parsing fails and triggers a JSONException, which is caught and displayed as “A JSONObject text must begin with ‘{‘…”. This confirms that the structure does not match a JSON object. The program then prints “The input is not a JSONObject. Checking if it’s a JSONArray…” and proceeds to the next parsing attempt. This time, the input is correctly parsed as a JSONArray, leading to the message “Successfully parsed as JSONArray!”. After this, the code iterates through each element in the array, printing “Iterating through JSONArray:” followed by the extracted details of each object: first “ID: 101, Name: Alice”, then “ID: 102, Name: Bob”. These lines come from reading the id and name fields within each JSON object in the array. Overall, the output reflects the entire control flow—incorrect parsing, error handling, successful array parsing, and final extraction and display of JSON data.

Sign up

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button