我有以下带有问题和答案选项的JSON文件。还有我尝试打印问题的代码。
{
"GameName": "millionaire game",
"level": 1,
"questions": [
{
"question1": "What is the minimum of players in a footbal game?",
"options1": [
8,
10,
9,
7
],
"answer1": "7"
},
{
"question2": "Who scored maximum goal footbal game?",
"options2": [
"Jhon",
"Pitty",
"Richard",
"Mike"
],
"answer2": "Mike"
},
{
"question3": "What is the maximum of players in a footbal game?",
"options3": [
8,
10,
9,
7
],
"answer3": "7"
}
]
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Random;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.*;
public class readJson {
public static void main(String[] args) throws JSONException {
String first = "jsonPerguntas2.json";
try {
String content = new String((Files.readAllBytes(Paths.get(first))));
JSONObject o = new JSONObject(content);
JSONArray firstQuestion = o.getJSONArray("question1");
//System.out.println(conteudo);
for (int i=0; i<firstQuestion.length(); i++){
System.out.println(firstQuestion.get(i));
}
} catch (IOException e) {
}
}
}
我有此代码可以读取文件。但是它总是返回相同的错误:
Exception in thread "main" org.json.JSONException: JSONObject["question1"] not found.
at org.json.JSONObject.get(JSONObject.java:454)
at org.json.JSONObject.getJSONArray(JSONObject.java:535)
at TrabPraticoJava.TesteLerJson.main(TesteLerJson.java:37)
C:\Users\José Dias\Documents\NetBeansProjects\TrabPraticoJava\nbproject\build-impl.xml:1341: The following error occurred while executing this line:
C:\Users\José Dias\Documents\NetBeansProjects\TrabPraticoJava\nbproject\build-impl.xml:936: Java returned: 1
BUILD FAILED (total time: 0 seconds)
如果我将JSONArray firstQuestion = o.getJSONArray("question1");
行更改为JSONArray firstQuestion = o.getJSONArray("questions");
,它实际上会打印所有文件,但我想单独打印问题。
有人可以帮我吗?在此先感谢
尝试一下:
JSONArray questions = o.getJSONArray("questions");
for (int i = 0; i < questions.length(); i++) {
JSONObject question = recs.getJSONObject(i);
System.out.println(question.getInt("question"+i+1));
}