How to Read a JSON Array File into Java Using the JSON.simple Library

Question

How can I effectively read a JSON array file in Java using the JSON.simple library?

[{
    "name":"John",
    "city":"Berlin",
    "cars":[
        "audi",
        "bmw"
    ],
    "job":"Teacher"
},
{
    "name":"Mark",
    "city":"Oslo",
    "cars":[
        "VW",
        "Toyota"
    ],
    "job":"Doctor"
}]

Answer

To read a JSON file that contains an array of objects using the JSON.simple library in Java, you need to correctly parse the structure of the JSON. The provided code mistakenly treats the entire JSON array as a single JSON object, which leads to a ClassCastException. Below is a detailed explanation and corrected code to read the JSON array properly.

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JavaApplication1 {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        try {  
            JSONArray jsonArray = (JSONArray) parser.parse(new FileReader("c:\\file.json"));
            for (Object obj : jsonArray) {
                JSONObject jsonObject = (JSONObject) obj;
                String name = (String) jsonObject.get("name");
                String city = (String) jsonObject.get("city");
                String job = (String) jsonObject.get("job");
                System.out.println("Name: " + name);
                System.out.println("City: " + city);
                System.out.println("Job: " + job);
                JSONArray cars = (JSONArray) jsonObject.get("cars");
                Iterator<String> iterator = cars.iterator();
                System.out.print("Cars: ");
                while (iterator.hasNext()) {
                    System.out.print(iterator.next() + " ");
                }
                System.out.println();  // New line for clarity
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Causes

  • The JSON file begins with a `[` character, indicating that the root element is an array, not an object. As a result, the file should be parsed into a JSONArray, not a JSONObject.

Solutions

  • Modify the parsing logic to handle the JSON array by directly casting the parsed object to a JSONArray.
  • Iterate through the JSONArray to access individual JSONObjects.

Common Mistakes

Mistake: Directly casting the parsed file to JSONObject when it is an array.

Solution: Change the casting to JSONArray and iterate over its elements.

Mistake: Not handling file path correctly in different operating systems.

Solution: Use double backslashes (\\) or forward slashes (/) to ensure compatibility across different platforms.

Helpers

  • read JSON file in Java
  • JSON.simple library Java
  • parse JSON array Java
  • Java read JSON example
  • Java JSON parsing errors

Related Questions

⦿How to Format an Integer with Leading Zeros in Java Using String.format

Learn how to format integers with leading zeros in Java using String.format method. Get examples and best practices.

⦿How Can You Use `string.startsWith()` Method While Ignoring Case in JavaScript?

Learn to use the string.startsWith method in JavaScript with case insensitivity along with examples and common mistakes.

⦿How to Convert Seconds into Hours, Minutes, and Seconds in Java?

Learn how to convert a BigDecimal seconds value into a formatted string displaying hours minutes and seconds in Java.

⦿Comparing @RunWith(MockitoJUnitRunner.class) and MockitoAnnotations.initMocks(this) in JUnit4 Tests

Learn the differences between RunWithMockitoJUnitRunner.class and MockitoAnnotations.initMocksthis in JUnit4 testing.

⦿How to Call Java from Python Efficiently?

Explore effective methods to call Java from Python including JPype and other alternatives without using Jython or RPC.

⦿Understanding the Difference Between Math.random() * n and Random.nextInt(n) in Java

Explore the differences between Math.random n and Random.nextIntn in Java including usage returns and best practices.

⦿How to Handle Date Parameters in a GET Request in Spring MVC Controller

Learn how to accept Date parameters in a GET request to a Spring MVC Controller using RequestParam with correct formatting.

⦿Understanding the Question Mark '?' and Colon ':' Operator in Java

Learn how the and operators work in Java their common usage and how they compare to ifelse statements.

⦿How to Handle ArrayList in Android Room Database Entity?

Learn how to save ArrayLists in Android Room Database entities using type converters and best practices.

⦿Understanding the Meaning of '->' in Gradle's Dependency Graph

Learn what the symbol indicates in Gradles dependency graph and how to resolve multiple dex file issues in Android.

© Copyright 2025 - CodingTechRoom.com