我是 JSON 的新手,我正在尝试将我的 JSON 文件解析为 Java,它可以工作,但我有包含更多数组的对象/数组,我不知道如何正确迭代它。
这是我的 JSON 文件:
{
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
},
"q2": {
"question": "12 - 8 = ?",
"options": [
"1",
"2",
"3",
"4"
],
"answer": "4"
}
}
}
}
我不知道如何获取此结构中的所有数据。我的意思是我知道这是一个测验,两个主题是运动和数学,每个主题都有问题和答案。
我希望每个值都可用。
这是我的 Java 代码
JSONParser jsonParser = new JSONParser();
try
{
JSONArray a = (JSONArray) jsonParser.parse("pathToFile");
for (Object o : a)
{
JSONObject task1 = (JSONObject) o;
String name = (String) task1.get("quiz");
System.out.println(name);
String topic = (String) task1.get("sport");
System.out.println(topic);
}
}catch (ParseException e)
{
e.printStackTrace();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
有人可以向我解释逻辑吗?
最佳答案
假设您不想使用 GSON 并在处理测验对象时放任自己的逻辑:
分析 JSON 并为值创建逻辑对象。
然后,当您读取 JSON 时,您可以根据需要创建对象并根据需要附加它们。
您需要测验、类别、问题和选项对象。
那么你的代码会变成这样(伪代码,没有测试它是否真的有效):
public Quiz createQuiz(JSONObject raw)
{
Quiz quiz = new Quiz();
Iterator<String> keys = raw.keys();
while(keys.hasNext()) {
String key = keys.next();
if (raw.get(key) instanceof JSONObject) {
JSONObject rawCategory = (JSONObject)raw.get(key);
quiz.addCategory(this.createCategory(key, rawCategory));
}
}
return quiz;
}
public Category createCategory(String name, JSONObject raw)
{
Category category = new Category(name);
Iterator<String> keys = raw.keys();
while(keys.hasNext()) {
String key = keys.next();
if (raw.get(key) instanceof JSONObject) {
JSONObject rawQuestion = (JSONObject)raw.get(key);
category.addQuestion(this.createQuestion(key, rawQuestion));
}
}
return category;
}
public Category createQuestion(String name, JSONObject raw)
{
Question question = new Question(name);
if(raw.hasKey("question") && raw.get("question") instanceof String) {
question.setQuestionText((String) raw.get("question"));
}
if(raw.hasKey("answer") && raw.get("answer") instanceof String) {
question.setAnswerText((String) raw.get("answer"));
}
if(raw.hasKey("options") && raw.get("options") instanceof JSONArray) {
JSONArray rawOptions = (JSONArray)raw.get("options");
for(Object rawOption : rawOptions) {
if(rawOption instanceof String) {
question.addOption(this.createOption((String) rawOption));
}
}
}
return question;
}
关于java - 将对象/数组从 JSON 解析为 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59989108/