You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSON嵌套对象/数组解析至Java:新手迭代逻辑求助

Fixing Nested JSON Parsing in Java for Your Quiz Structure

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):

  1. Parse the JSON file into a top-level JSONObject
  2. Extract the quiz JSONObject from the top-level object
  3. Iterate over each topic (sport, maths) in the quiz object
  4. For each topic, iterate over its questions (q1, q2)
  5. Extract question details, including the options array, 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 options array, we use a standard for loop with length() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:17:29