working solution

JSONParser parser = new JSONParser();
JSONObject jsonObject;
try {

    jsonObject = (JSONObject) parser.parse(new FileReader("E:\\json.txt"));

    out.println("<br>"+jsonObject);


    JSONArray from_excel = (JSONArray)jsonObject.get("from_excel");
    // for row output 1
    for(Object o: from_excel){
        out.println("<br>"+o);
    }
    // for row output 2
    Iterator iterator = from_excel.iterator();
    while (iterator.hasNext()) {
        out.println("<br>"+iterator.next());
    }
    // for item output 3
    for (int i = 0; i < from_excel.size(); i++) {

        JSONObject jsonObjectRow = (JSONObject) from_excel.get(i);
        String num = (String) jsonObjectRow.get("num");
        String solution = (String) jsonObjectRow.get("solution");
        out.println("<br>num="+num+"; solution="+solution);
    }
} catch (Exception e) {
    out.println("Error: "+e);
}
Answer from Nikolay Baranenko on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-read-parse-json-array-using-java
How to read/parse JSON array using Java?
May 5, 2025 - 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 ReadingArrayFromJSON { public static void main(String args[]) { //Creating a JSONParser object JSONParser jsonParser = new JSONParser(); try { //Parsing the contents of the JSON file JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/test.json")); //Forming URL System.out.println("Conten
🌐
Kodejava
kodejava.org › how-do-i-read-json-file-using-json-java-org-json-library
How do I read JSON file using JSON-Java (org.json) library? - Learn Java by Examples
We can use method like getString(), getInt(), getLong(), etc. to read a key-value from the JSON file. The getJSONArray() method allow us to read a list of values returned in JSONArray object, which can be iterated to get each values represented ...
🌐
Coderanch
coderanch.com › t › 648260 › java › parsing-file-JSON-array
Need help parsing a file (JSON) with an array (Beginning Java forum at Coderanch)
April 4, 2015 - Either: 1) The library supports a compound reference, such as "references.hexes" to reference something that isn't at the top level. 2) You will have to call get(...) multiple times to drill down into the data. Incidentally, there is a method called getJsonObject(String key) that will return ...
🌐
Delft Stack
delftstack.com › home › howto › java › handling json arrays in java
How to Handle JSON Arrays in Java | Delft Stack
February 2, 2024 - Once the file is open, its object is passed to the FileReader() constructor. We use a JSON parser that returns a Java Object to parse the JSON content. We should use an explicit cast to cast a JSON Array.
Find elsewhere
🌐
Delft Stack
delftstack.com › home › howto › java › read json file java
How to Read JSON File in Java | Delft Stack
February 2, 2024 - To parse the content of this file, we will use the json.simple java library. We need to import two classes from the java.simple library, the org.json.simple.JSONArray and org.json.simple.JSONObject class. The JSONArray helps us read elements in the form of an array, and the JSONObject helps us read the objects present in the JSON text.
🌐
YouTube
youtube.com › code, etc.
Read JSON Object and JSON Array From File with Java - YouTube
Buy me a coffe?https://ko-fi.com/bielsyah🇮🇩 Traktir saya?https://trakteer.id/bielsyahLibraries :https://depositfiles.com/files/wp0zd5bat0:00 Intro0:12 Read...
Published: August 17, 2022
Views: 484
🌐
Attacomsian
attacomsian.com › blog › jackson-read-json-file
How to Read JSON from a file using Jackson
October 14, 2022 - [ { "title": "Thinking in Java", ... } ] You can now read a list of Book objects from the above JSON file using the same readValue() method as shown below: try { // create object mapper instance ObjectMapper mapper = new ...
🌐
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.
🌐
DZone
dzone.com › coding › languages › read/write a raw json, array-like json, and map-like json file as an object
Read/Write a Raw JSON, Array-Like JSON, and Map-Like JSON File as an Object
April 22, 2020 - In this article, you have a supersonic guide for reading/writing a JSON file via JSON-B, Jackson, and Gson. Let's start with three text files that represent typical JSON-like mappings: In melons_raw.json , we have a JSON entry per line. Each line is a piece of JSON that's independent of the previous line but has the same schema. In melons_array.json , we have a JSON array, and in melons_map.json , we have a JSON that fits well in a Java Map .
🌐
Attacomsian
attacomsian.com › blog › gson-read-json-file
How to read JSON from a file using Gson in Java
October 14, 2022 - try { // create Gson instance Gson gson = new Gson(); // create a reader Reader reader = Files.newBufferedReader(Paths.get("user.json")); // convert a JSON string to a User object User user = gson.fromJson(reader,User.class); // print user object System.out.println(user); // close reader reader.close(); } catch (Exception ex) { ex.printStackTrace(); } You should see the following output printed on the console: User{name='John Doe', email='john.doe@example.com', roles=[Member, Admin], admin=true} Let us say we have the following JSON file called users.json that contains a JSON array:
Top answer
1 of 3
6
  1. Create a POJO class to represent your JSON data:

    public class CarInfo {  
      String car;
      String colour;
      String qty;
      String date_manufactured; 
    }
    
  2. Use GSON to parse JSON String Array

    String carInfoJson = "[{ \"car\": \"Toyota\", \"colour\": \"red\",\"qty\": \"1\",\"date_manufactured\":\"12972632260006\" }, { \"car\":\"Hyundai\", \"colour\":\"red\",\"qty\":\"2\",\"date_manufactured\":\"1360421626000\" }]";
    Gson gson = new Gson();  
    CarInfo[] carInfoArray = gson.fromJson(carInfoJson, CarInfo[].class);  
    
  3. Use GSON to parse JSON String Array from a file

    String carInfoJson= new String(Files.readAllBytes(Paths.get("filename.txt")));
    Gson gson = new Gson();  
    CarInfo[] carInfoArray = gson.fromJson(carInfoJson, CarInfo[].class);
    
  4. Use GSON to parse JSON String Array from a file using BufferedReader

    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new FileReader(file));
      Gson gson = new Gson(); 
      CarInfo[] carInfoArray = gson.fromJson(reader, CarInfo[].class);
    } catch (FileNotFoundException ex) {
      ...
    } finally {
      ...
    }
    
  5. Use GSON to parse JSON String Array from a file using JsonReader in stream mode

    try {
      InputStream stream = new FileInputStream("c:\\filename.txt");
      JsonReader reader = new JsonReader(new InputStreamReader(stream, "UTF-8"));
      Gson gson = new Gson();
    
      // Read file in stream mode
      reader.beginArray();
      while (reader.hasNext()) {
        CarInfo carInfo = gson.fromJson(reader, CarInfo.class);
      }
      reader.endArray();
      reader.close();
    } catch (UnsupportedEncodingException ex) {
      ...
    } catch (IOException ex) {
      ...
    }
    
2 of 3
0

I'm using json-simple to explain how to do this. Your json is a JSONArray (because it starts and ends with square brackets) with JSONObject (curly brackets with pair list) inside so first you've to extract the array using a JSONParser and then you can easily iterate over it and get fields from each JSONObject. Here is a simple example it just shows you an easy and understandable way:

String json = "[{ \"car\": \"Toyota\", \"colour\": \"red\", \"qty\": \"1\",\"date_manufactured\":\"12972632260006\" }, { \"car\": \"Hyundai\", \"colour\": \"red\", \"qty\": \"2\",\"date_manufactured\":\"1360421626000\" }]";
JSONParser parser = new JSONParser();
try {
    /* It's a JSONArray first. */
    JSONArray tmpArr = (JSONArray)parser.parse(json);
    for(Object obj : tmpArr){
        /* Extract each JSONObject */
        JSONObject tmpObj = (JSONObject) obj;
        System.out.println(tmpObj.get("car"));
        System.out.println(tmpObj.get("colour"));
        System.out.println(tmpObj.get("qty"));
        System.out.println(tmpObj.get("date_manufactured"));
    }
} catch (ParseException e) {
    e.printStackTrace();
}

Note that you can use Gson, it's much more complete then json-simple but a little bit trickier.

🌐
Crunchify
crunchify.com › how-to-read-json-object-from-file-in-java
How to Read JSON Object From File in Java?
February 16, 2023 - We cannot provide a description for this page right now
🌐
CodeSignal
codesignal.com › learn › courses › handling-json-files-with-java › lessons › working-with-json-in-java-advanced-parsing-techniques
Accessing JSON Data with Java
Remember, mastering these skills is crucial for effectively handling data in Java applications. Happy coding! ... Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignalStart learning today! ... { "school": "Greenwood High", "location": { "city": "New York", "state": "NY" }, "students": [ {"name": "Emma", "age": 15}, {"name": "Liam", "age": 14} ] } ... // Path to the JSON file Path filePath = Paths.get("data.json"); // Read the entire content of the JSON file into a string String json = Files.readString(filePath); // Create ObjectMapper instance ObjectMapper objectMapper = new ObjectMapper(); // Parse the JSON string into a JsonNode JsonNode rootNode = objectMapper.readTree(json);
Top answer
1 of 4
2

You can use gson library

You can use Maven or jar file: http://mvnrepository.com/artifact/com.google.code.gson/gson

package com.test;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class AppJsonTest {

    public static void main(String[] args) {
        List<DataObject> objList = new ArrayList<DataObject>();
        objList.add(new DataObject(1, "Coca Cola", 0.9, 19));
        objList.add(new DataObject(2, "Coca Cola Zero", 0.6, 19));

        // Convert the object to a JSON string
        String json = new Gson().toJson(objList);
        System.out.println(json);

        // Now convert the JSON string back to your java object
        Type type = new TypeToken<List<DataObject>>() {
        }.getType();
        List<DataObject> inpList = new Gson().fromJson(json, type);
        for (int i = 0; i < inpList.size(); i++) {
            DataObject x = inpList.get(i);
            System.out.println(x.toString());
        }
    }
}

class DataObject {
    int idProducto;
    String Nombre;
    Double Precio;
    int Cantidad;

    public DataObject(int idProducto, String nombre, Double precio, int cantidad) {
        this.idProducto = idProducto;
        Nombre = nombre;
        Precio = precio;
        Cantidad = cantidad;
    }

    public int getIdProducto() {
        return idProducto;
    }

    public void setIdProducto(int idProducto) {
        this.idProducto = idProducto;
    }

    public String getNombre() {
        return Nombre;
    }

    public void setNombre(String nombre) {
        Nombre = nombre;
    }

    public Double getPrecio() {
        return Precio;
    }

    public void setPrecio(Double precio) {
        Precio = precio;
    }

    public int getCantidad() {
        return Cantidad;
    }

    public void setCantidad(int cantidad) {
        Cantidad = cantidad;
    }

    @Override
    public String toString() {
        return "DataObject [idProducto=" + idProducto + ", Nombre=" + Nombre + ", Precio=" + Precio + ", Cantidad=" + Cantidad + "]";
    }

}
2 of 4
1

Use gson library to read and write json:

 try {
            JsonReader reader = new JsonReader(new FileReader("json_file_path.json"));

            reader.beginArray();
            while (reader.hasNext()) {

                reader.beginObject();
                while (reader.hasNext()) {

                    String name = reader.nextName();

                    if (name.equals("idProducto")) {

                        System.out.println(reader.nextInt());

                    } else if (name.equals("Nombre")) {

                        System.out.println(reader.nextString());

                    } else if (name.equals("Precio")) {

                        System.out.println(reader.nextDouble());

                    } else if (name.equals("Cantidad")) {
                        System.out.println(reader.nextInt());
                    } else {
                        reader.skipValue();
                    }
                }
                reader.endObject();
            }
            reader.endArray();

            reader.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

download http://www.java2s.com/Code/JarDownload/gson/gson-2.2.2.jar.zip

Top answer
1 of 2
1

You could use this library:

http://www.json.org/java/

Then you can read the file into a String used a BufferedReader, close the reader and do something like this:

JSONArray ja = new JSONOArray(string);
int[][] result = new int[ja.length()][];
for (int i = 0; i < ja.length(); i++) {
    JSONAarray ja2 = ja.getJSONArray(i);
    result[i] = new int[ja2.length()];
    for (int j = 0; j < ja2.length(); j++) {
        result[i][j]=ja2.getInt(j);
    }
}

I haven't tested this code, and you also might want to add some error checking and extract local variables, depending on how sure you are the file is in the right format. This does not assume your file contains a rectangular matrix.

2 of 2
1

If you have JSON as input and want to convert it to a Java 2D array you can easily convert your JSON input using the Jackson library. Jackson can convert JSON to POJOs and POJOs to JSON and this is called deserialization/serialization.

The main class used for mapping between JSON and POJOs is the ObjectMapper. To convert from a JSON String to a 2D array of ints the following Java code can be used:

final String json = "[[1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]";

// Create a Jackson mapper
ObjectMapper mapper = new ObjectMapper();

// Map the JSON to a 2D array
final int[][] ints = mapper.readValue(json, int[][].class);

The only dependencies required to run Jackson is:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version> <!-- At the time of writing -->
</dependency>
🌐
Devstringx
devstringx.com › read-data-from-json
How to Read Data from JSON file Using JAVA? - Devstringx
April 15, 2026 - For example, you can retrieve values ... ordered lists of values. To read JSON arrays, you need to recapitulate over the array elements and access each value independently....