How to read a JSON file using java

To read a JSON file using Java, you can use the org.json library. Here’s an example of how you can use this library to read a JSON file:

read a json file using java
Complete code to read a JSON file using java
import org.json.JSONObject;
import org.json.JSONArray;

import java.io.FileReader;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) throws Exception {
        // Read the JSON file
        FileReader reader = new FileReader("file.json");

        // Parse the JSON file
        JSONObject json = new JSONObject(reader);

        // Get the JSON array
        JSONArray array = json.getJSONArray("array");

        // Iterate over the array
        for (int i = 0; i < array.length(); i++) {
            // Get the object at the current index
            JSONObject object = array.getJSONObject(i);

            // Get the value of the "key" field
            String key = object.getString("key");

            // Print the value of the "key" field
            System.out.println(key);
        }
    }
}

This code reads a JSON file called file.json and prints the value of the “key” field for each object in the “array” array.

I hope this helps! Let me know if you have any questions.


Discover more from Automation Script

Subscribe to get the latest posts sent to your email.

Related Posts