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)

1

1 Answer 1

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();
        }

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It works with the path of the file instead of the string as path

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.