The whole file is an array and there are objects and other arrays (e.g. cars) in the whole array of the file.

As you say, the outermost layer of your JSON blob is an array. Therefore, your parser will return a JSONArray. You can then get JSONObjects from the array ...

  JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));

  for (Object o : a)
  {
    JSONObject person = (JSONObject) o;

    String name = (String) person.get("name");
    System.out.println(name);

    String city = (String) person.get("city");
    System.out.println(city);

    String job = (String) person.get("job");
    System.out.println(job);

    JSONArray cars = (JSONArray) person.get("cars");

    for (Object c : cars)
    {
      System.out.println(c+"");
    }
  }

For reference, see "Example 1" on the json-simple decoding example page.

Answer from Greg Kopff on Stack Overflow
🌐
DigitalOcean
digitalocean.com › community › tutorials › jackson-json-java-parser-api-example-tutorial
Jackson JSON Java Parser API Example Tutorial | DigitalOcean
August 3, 2022 - Jackson JSON Parser API provides easy way to convert JSON to POJO Object and supports easy conversion to Map from JSON data. Jackson supports generics too and directly converts them from JSON to object. For our example for JSON to POJO/Java object conversion, we will take a complex example with nested object and arrays. We will use arrays, list and Map in java objects for conversion. Our complex json is stored in a file employee.txt with below structure:
🌐
Medium
medium.com › @AlexanderObregon › javas-jsonparser-parse-method-explained-76b126f6110e
Java’s JsonParser.parse() Method Explained | Medium
October 13, 2024 - Similar to the previous example, readObject() processes the file and converts the content into a JsonObject. Another common scenario is reading JSON data from an API response. Here’s a simplified example where you simulate fetching JSON data from a URL (in real-world use cases, you would likely be using a library like HttpClient or HttpURLConnection to make the HTTP request). import javax.json.Json; import javax.json.JsonReader; import javax.json.JsonObject; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class JsonApiParserExample { public static v
🌐
GeeksforGeeks
geeksforgeeks.org › java › parse-json-java
How to parse JSON in Java - GeeksforGeeks
December 23, 2025 - import java.io.FileReader; import java.util.Iterator; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class JSONReadExample { public static void main(String[] args) throws Exception { Object obj = new JSONParser().parse(new FileReader("JSONExample.json")); JSONObject jo = (JSONObject) obj; String firstName = (String) jo.get("firstName"); String lastName = (String) jo.get("lastName"); long age = (long) jo.get("age"); System.out.println(firstName); System.out.println(lastName); System.out.println(age); Ma
🌐
DZone
dzone.com › coding › java › how to read and parse a json file in java
How to Read and Parse a JSON File in Java
March 6, 2025 - To read the JSON file in Java, FileReader() method is used to read the given JSON file. ... The above code is the file that is used to read. we use the json.simple library. ... //program for reading a JSON file import org.json.simple.JSONArray; ...
🌐
Mkyong
mkyong.com › home › java › read and write json using json.simple
Read and write JSON using JSON.simple - Mkyong.com
May 13, 2024 - The following example uses JSON.simple to read JSON from a file named person.json and print out the values. ... package com.mkyong.json.jsonsimple; import com.github.cliftonlabs.json_simple.JsonArray; import com.github.cliftonlabs.json_simple.JsonException; import com.github.cliftonlabs.json_simple.JsonObject; import com.github.cliftonlabs.json_simple.Jsoner; import java.io.FileReader; import java.io.IOException; public class JsonSimpleReadExample1 { public static void main(String[] args) { try (FileReader reader = new FileReader("person.json")) { JsonObject jsonObject = (JsonObject) Jsoner.de
Top answer
1 of 16
962

The org.json library is easy to use.

Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation

  • [ … ] represents an array, so library will parse it to JSONArray
  • { … } represents an object, so library will parse it to JSONObject

Example code below:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

You may find more examples from: Parse JSON in Java

Downloadable jar: http://mvnrepository.com/artifact/org.json/json

2 of 16
714

For the sake of the example lets assume you have a class Person with just a name.

private class Person {
    public String name;

    public Person(String name) {
        this.name = name;
    }
}

Jackson (Maven)

My personal favourite and probably the most widely used.

ObjectMapper mapper = new ObjectMapper();

// De-serialize to an object
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);
System.out.println(user.name); //John

// Read a single attribute
JsonNode nameNode = mapper.readTree("{\"name\": \"John\"}");
System.out.println(nameNode.get("name").asText());

Google GSON (Maven)

Gson g = new Gson();

// De-serialize to an object
Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John

// Read a single attribute
JsonObject jsonObject = new JsonParser().parseString("{\"name\": \"John\"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John

Org.JSON (Maven)

This suggestion is listed here simply because it appears to be quite popular due to stackoverflow reference to it. I would not recommend using it as it is more a proof-of-concept project than an actual library.

JSONObject obj = new JSONObject("{\"name\": \"John\"}");

System.out.println(obj.getString("name")); //John
Find elsewhere
🌐
How to do in Java
howtodoinjava.com › home › java libraries › json.simple – read and write json
JSON.simple - Read and Write JSON in Java
October 1, 2022 - To read JSON from file, we will use the JSON file we created in the previous example. First of all, we will create JSONParser instance to parse JSON file. Use FileReader to read JSON file and pass it to parser.
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-read-a-json-file-in-java
How can we read a JSON file in Java?
In order to read a JSON file, we need to download the json-simple.jar file and set the path to execute it. import java.io.*; import java.util.*; import org.json.simple.*; import org.json.simple.parser.*; public class JSONReadFromTheFileTest { public static void main(String[] args) { JSONParser ...
🌐
Medium
vajithc.medium.com › parsing-json-without-libraries-build-your-own-json-reader-in-java-1db8e6165039
Parsing JSON Without Libraries: Build Your Own JSON Reader in Java | by Vajithc | Medium
April 4, 2025 - Place a sample JSON file in your resources directory, for example: { "name": "Alice", "age": 25, "hobbies": ["reading", "traveling"] } ... The fundamentals of JSON parsing. Techniques for handling nested data structures in Java. The art of building robust utilities from scratch.
🌐
YouTube
youtube.com › watch
A quick tutorial on using JSON-simple parsing JSON ...
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
Crunchify
crunchify.com › json tutorials › how to read json object from file in java?
How to Read JSON Object From File in Java? • Crunchify
February 16, 2023 - Hi Ashok – I hope this tutorial will help: https://crunchify.com/simple-oracle-database-jdbc-connect-and-executequery-example-in-java/ ... Here I am having one problem, if I have array of objects, then how can I read those JSON objects from array ? ... Object obj = parser.parse(new FileReader(COLLECTION_FILE_NAME)); JSONArray mainArray = (JSONArray) obj;
Top answer
1 of 7
10

Using the json.org reference implementation (org.json homepage, Download here). The code is a bit messy but I think it does what you are asking for. You can take alot of shortcuts by not creating all this objects but to access them directly. The reason that I do it this way is an attempt to make it easier to follow whats happening.

package com.mypackage;

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

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"status\": \"OK\",\"origin_addresses\": [ \"Vancouver, BC, Canada\", \"Seattle, État de Washington, États-Unis\" ],\"destination_addresses\": [ \"San Francisco, Californie, États-Unis\", \"Victoria, BC, Canada\" ],\"rows\": [ {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 340110,\"text\": \"3 jours 22 heures\"},\"distance\": {\"value\": 1734542,\"text\": \"1 735 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 24487,\"text\": \"6 heures 48 minutes\"},\"distance\": {\"value\": 129324,\"text\": \"129 km\"}} ]}, {\"elements\": [ {\"status\": \"OK\",\"duration\": {\"value\": 288834,\"text\": \"3 jours 8 heures\"},\"distance\": {\"value\": 1489604,\"text\": \"1 490 km\"}}, {\"status\": \"OK\",\"duration\": {\"value\": 14388,\"text\": \"4 heures 0 minutes\"},\"distance\": {\"value\": 135822,\"text\": \"136 km\"}} ]} ]}";

        try {
            JSONObject rootObject = new JSONObject(jsonStr); // Parse the JSON to a JSONObject
            JSONArray rows = rootObject.getJSONArray("rows"); // Get all JSONArray rows

            for(int i=0; i < rows.length(); i++) { // Loop over each each row
                JSONObject row = rows.getJSONObject(i); // Get row object
                JSONArray elements = row.getJSONArray("elements"); // Get all elements for each row as an array

                for(int j=0; j < elements.length(); j++) { // Iterate each element in the elements array
                    JSONObject element =  elements.getJSONObject(j); // Get the element object
                    JSONObject duration = element.getJSONObject("duration"); // Get duration sub object
                    JSONObject distance = element.getJSONObject("distance"); // Get distance sub object

                    System.out.println("Duration: " + duration.getInt("value")); // Print int value
                    System.out.println("Distance: " + distance.getInt("value")); // Print int value
                }
            }
        } catch (JSONException e) {
            // JSON Parsing error
            e.printStackTrace();
        }
    }
}
2 of 7
6
  1. Create an class structure that reflects the JSON
  2. Use a library like Jackson or GSON to deserialize the json to instances of your classes.

If you want a more dynamic approach, the above frameworks can also serialize to maps.

🌐
Oracle
oracle.com › java › technical details
Java API for JSON Processing
The Java API for JSON Processing provides portable APIs to parse, generate, transform, and query JSON.
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › stream › JsonParser.html
JsonParser (Java(TM) EE 7 Specification APIs)
Provides forward, read-only access to JSON data in a streaming way. This is the most efficient way for reading JSON data. The class Json contains methods to create parsers from input sources (InputStream and Reader).
🌐
DevQA
devqa.io › how-to-parse-json-in-java
How to Parse JSON in Java
Also, note that “pageInfo” ... getJSONArray method. ... In order to use Gson to parse JSON in Java, you need to add the library as a dependency....
🌐
LabEx
labex.io › tutorials › java-how-to-read-json-file-from-relative-path-in-java-417587
How to read JSON file from relative path in Java | LabEx
When running a Maven project from the terminal, the working directory is typically the project's root folder, which is ~/project in our case. Therefore, the relative path to our JSON file is src/main/resources/data.json. Let's create a Java class to read the file.