JSON嵌套对象/数组解析至Java:新手迭代逻辑求助
Hey there! I see you're getting the hang of basic JSON parsing in Java, but stuck on navigating nested objects and arrays. Let's fix your code and walk through the correct iteration logic step by step.
First, Let's Spot the Issues in Your Current Code
Your JSON's outermost element is a JSONObject (not a JSONArray), but your code tries to cast the parsed result to JSONArray—that's a key mistake. Also, you're trying to cast nested objects like quiz and sport to String, which will throw type errors since those are actually JSONObjects.
Step-by-Step Correct Approach
Let's break down how to traverse your nested JSON structure properly (using the org.json library you're already using):
- Parse the JSON file into a top-level JSONObject
- Extract the
quizJSONObject from the top-level object - Iterate over each topic (sport, maths) in the quiz object
- For each topic, iterate over its questions (q1, q2)
- Extract question details, including the
optionsarray, and iterate through the options
Corrected Java Code
import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONParser; import org.json.ParseException; import java.io.FileReader; import java.io.IOException; import java.util.Map; public class QuizJsonParser { public static void main(String[] args) { JSONParser jsonParser = new JSONParser(); String filePath = "pathToFile"; // Replace with your actual file path try (FileReader reader = new FileReader(filePath)) { // Step 1: Parse the entire JSON file into a top-level JSONObject JSONObject topLevelObj = (JSONObject) jsonParser.parse(reader); // Step 2: Get the "quiz" nested JSONObject JSONObject quizObj = topLevelObj.getJSONObject("quiz"); // Step 3: Iterate over each topic (sport, maths) in the quiz for (Map.Entry<String, Object> topicEntry : quizObj.entrySet()) { String topicName = topicEntry.getKey(); JSONObject topicQuestions = (JSONObject) topicEntry.getValue(); System.out.println("=== Topic: " + topicName + " ==="); // Step 4: Iterate over each question in the current topic for (Map.Entry<String, Object> questionEntry : topicQuestions.entrySet()) { String questionId = questionEntry.getKey(); JSONObject questionDetails = (JSONObject) questionEntry.getValue(); System.out.println("\nQuestion " + questionId + ": " + questionDetails.getString("question")); System.out.println("Correct Answer: " + questionDetails.getString("answer")); // Step 5: Iterate over the "options" array JSONArray optionsArray = questionDetails.getJSONArray("options"); System.out.println("Options:"); for (int i = 0; i < optionsArray.length(); i++) { System.out.println(" " + (i + 1) + ". " + optionsArray.getString(i)); } } } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Key Explanations
- Using
entrySet()for iteration: This lets us get both the key (like "sport", "q1") and the corresponding value (the nested object) for each element in a JSONObject, which is perfect for dynamic structures where you don't know all the keys upfront. - Casting to the right type: Every time we extract a value from a JSONObject, we cast it to the correct type (JSONObject for nested objects, JSONArray for arrays, String for text values) to avoid type errors.
- Iterating over JSONArray: For the
optionsarray, we use a standard for loop withlength()to access each element by index.
Output Preview
When you run this code, you'll get a clean breakdown like this:
=== Topic: sport === Question q1: Which one is correct team name in NBA? Correct Answer: Huston Rocket Options: 1. New York Bulls 2. Los Angeles Kings 3. Golden State Warriros 4. Huston Rocket === Topic: maths === Question q1: 5 + 7 = ? Correct Answer: 12 Options: 1. 10 2. 11 3. 12 4. 13 Question q2: 12 - 8 = ? Correct Answer: 4 Options: 1. 1 2. 2 3. 4
内容的提问来源于stack exchange,提问作者Marie_Jane98

