1

So, I am using json-simple library in my project, and this is what I have right now: (I just want to print out each of the objects from the JSON file)

import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;

public class App {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        try {
            Object obj = parser.parse(new FileReader("src/movies.json"));
            JSONObject jsonObject = (JSONObject) obj;

            JSONArray upcoming = (JSONArray) jsonObject.get("Upcoming");
            JSONArray current = (JSONArray) jsonObject.get("Current");

            System.out.println("Upcoming Movies:");
            Iterator upcomingIterator = upcoming.iterator();
            
            while (upcomingIterator.hasNext()) {
                String title = (String) ((HashMap) upcomingIterator.next()).get("title");
                System.out.println("title: " + title);

                String numberOfSeats = (String) ((HashMap) upcomingIterator.next()).get("numberOfSeats");
                System.out.println("numberOfSeats: " + numberOfSeats);

                String synopsis = (String) ((HashMap) upcomingIterator.next()).get("synopsis");
                System.out.println("synopsis: " + synopsis);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

and this is what the JSON file looks like:

{
    "Upcoming": [
        {
            "title": "Black Panther: Wakanda Forever",
            "status": "Current",
            "showtimes": [
                "11:00",
                "12:00",
                "13:00"
            ],
            "theater": [
                "Lubbock",
                "Amarillo",
                "Plainview",
                "Snyder"
            ],
            "numberOfSeats": "55",
            "synopsis": "The people of Wakanda fight to protect their home from intervening world powers as they mourn the death of King T'Challa.",
            "runtime": "161 min",
            "prices": [
                "$5",
                "$6",
                "$10"
            ],
            "reviews": [
                "Great Movie",
                "Best Movie",
                "The greatest movie ever",
                "I like the lead in this movie"
            ],
            "castInfo": [
                "Letitia Wright",
                "Lupita Nyong'o",
                "Danai Gurira",
                "Winston Duke"
            ]
        },
        {
            "title": "Thor: Love and Thunder",
            "status": "Upcoming",
            "showtimes": [
                "14:30",
                "19:15",
                "19:45"
            ],
            "theater": [
                "Lubbock",
                "Plainview",
                "Abilene"
            ],
            "numberOfSeats": "64",
            "synopsis": "Thor enlists the help of Valkyrie, Korg and ex-girlfriend Jane Foster to fight Gorr the God Butcher, who intends to make the gods extinct.",
            "runtime": "118 min",
            "prices": [
                "$6",
                "$7",
                "$10"
            ],
            "reviews": [
                "Great Movie",
                "Best Movie",
                "The greatest movie ever",
                "I like the lead in this movie"
            ],
            "castInfo": [
                "Chris Hemsworth",
                "Natalie Portman",
                "Christian Bale",
                "Tessa Thompson"
            ]
        }
    ]
}

After running the code above, I am getting the following output which is not really consistent with the JSON data. Can someone please explain how can I solve this?

Output

Nomad312
  • 13
  • 4
  • for those who voted for close: this question is not about how to iterate over json. – dermoritz Dec 02 '22 at 12:20
  • You're calling `upcomingIterator.next()` three times in the loop, while `Upcoming` only contains 2 elements. You should call `next()` only **once** per loop iteration, assign it to a local variable, and then use it for the remainder of the loop. In case you hadn't noticed it, you printed the title of the first array element of `Upcoming`, and the number of seats of the second array element. If you had had three elements in the array, you would have printed the synopsis of the third. – Mark Rotteveel Dec 09 '22 at 13:36

1 Answers1

1

in the loop you use "jsonObject" but i guess you should use "upcomingIterator.next()"

        while (upcomingIterator.hasNext()) {
            String title = (String) upcomingIterator.next().get("title");
            System.out.println("title: " + title);
        }

I am not sure about the JSON API u are using, but it is sure if you use hasNext() you want most likely use next() to actually iterate and let the loop stop if there is no next anymore.

Some other point to mention (you seem to begin with Java?): never ever

catch (Exception e) {
    e.printStackTrace();
}

but instead:

catch (Exception e) {
    throw new IllegalArgumentException("Problem on reading JSON: " , e);
}

Don't ask why most IDEs put this as default in catch block (i think at least IntelliJ changed).

dermoritz
  • 12,519
  • 25
  • 97
  • 185
  • This helped, thank you so much for your prompt response! Also, it seems that I also need to do a casting like this: `String title = (String) ((HashMap) upcomingIterator.next()).get("title");` – Nomad312 Dec 02 '22 at 08:00
  • Thank you for the tip, I have implemented that as well! – Nomad312 Dec 02 '22 at 08:06
  • please accept the answer if it is working. The next step i would take is to create classes like "Event" or whatever and then map JSON into these classes by using JSON<->Object Mapper. – dermoritz Dec 02 '22 at 08:27