0

I would like to print all the json objects that are in a particular json file. My function receive a string that is the path of a json within my project. movieListJSON is the path of my json.

This is my folder structure:

templates
 *fetchIMDB.java
 *Movie.class
movies.json

That is what i tried so far, but I dont find a way to open the json and iterate through the values by the key.

public void fetchIMDBMovies(String movieListJSON, String outputDir) throws IOException {
    // 
    JSONObject jsonObject;
    System.out.println(movieListJSON);
    JSONParser parser = new JSONParser();
    InputStream in = getClass().getResourceAsStream(movieListJSON);
}

My json file looks like:

    [
 {
  "movie_name": "Avatar"
 },
 {
  "movie_name": "Star Wars VII: The Force Awakens"
 },
 {
  "movie_name": "Pirates of the Caribbean: At World's End"
 },
 {
  "movie_name": "Spectre"
 },
 {
  "movie_name": "The Dark Knight Rises"
 }
]

How can I get all the json with value movie_name and print them all using System.out.println();

I want to print the movie names (value of the movie_name in json)

Miguel Bets
  • 181
  • 1
  • 10
  • This - or simple variations on it - have been answered before. See https://stackoverflow.com/questions/10926353/how-to-read-json-file-into-java-with-simple-json-library – JohnXF Apr 22 '21 at 13:51

1 Answers1

2

Here is the solution.

Instead of 'your-path' enter the path to your file. If you use Intelij Idea, you can get it by Right click on file + Copy path... + Copy relative path (or full path, as you want)

 try {
            JSONArray array = (JSONArray) new JSONParser().parse(new FileReader("your-path"));
            for (Object temp : array) {
                JSONObject jsonObject = (JSONObject) temp;
                System.out.println(jsonObject.get("movie_name"));
            }
        } catch (IOException | ParseException  e) {
            e.printStackTrace();
        }

Anna S
  • 58
  • 6