java - 如何在 Java 中解析这个 JSON?
问题描述
我目前正在为 android 开发一个测试应用程序,需要解析 JSON 测试数据。
JSON 看起来像这样:
{"id":1,"name":"Test Test","questions":[{"id":1,"test":1,"text":"Kannst du diese Frage beantworten?","answers":[{"id":1,"question":1,"text":"Ja, das ist richtig.","correct":1},{"id":2,"question":1,"text":"Diese Antwort ist falsch.","correct":0},{"id":3,"question":1,"text":"Diese hier ist ebenfalls nicht so ganz korrekt.","correct":0}]},{"id":2,"test":1,"text":"Diese Frage hier ist nicht korrekt.","answers":[{"id":4,"question":2,"text":"Ich glaube dir nicht, das hier ist eh richtig.","correct":1},{"id":5,"question":2,"text":"Diese Antwort ist falsch.","correct":0},{"id":6,"question":2,"text":"Diese hier ist ebenfalls nicht so ganz korrekt.","correct":0}]}]}
我需要的是提取问题及其子数据。
我尝试的是:
JSONObject jObject = new JSONObject(result);
String test = jObject.getJSONObject("id").getJSONArray("questions").toString();
和
String myString = jObject .getJSONObject("questions").getJSONObject("answers").getString("text");
解决方案
像这样解析您的数据:
public class DataModel {
int id;
String name;
ArrayList<Question> questions = new ArrayList<>();
public class Question {
int id;
int test;
String text;
ArrayList<Answers> answers = new ArrayList<>();
}
public class Answers {
int id;
int question;
String text;
int correct;
}
public DataModel parseResponce(JSONObject response) {
id = response.optInt("id");
name = response.optString("name");
JSONArray array = response.optJSONArray("questions");
parseQuestion(array);
return this;
}
public void parseQuestion(JSONArray questions) {
for (int i = 0; i < questions.length(); i++) {
JSONObject object = questions.optJSONObject(i);
Question question = new Question();
question.id = object.optInt("id");
question.test = object.optInt("test");
question.text = object.optString("text");
JSONArray array = object.optJSONArray("answers");
for (int j = 0; j < array.length(); j++) {
JSONObject answer = questions.optJSONObject(i);
Answers ans = new Answers();
ans.id = answer.optInt("id");
ans.question = answer.optInt("question");
ans.text = answer.optString("text");
ans.correct = answer.optInt("correct");
question.answers.add(ans);
}
this.questions.add(question);
}
}
}
只需调用 parseResponce(JSONObject response) 方法并将响应传递给您,您将在 DataModel 对象中获得问题和答案;
推荐阅读
- javascript - 将具有相同前缀的对象键拆分为新对象
- spring-boot - 在 Spring Boot 中为 FileUpload 编写包装器:文件不存在
- python - Pytest 在测试期间使用开发 sqlite db - NoneType 对象没有属性驱动程序名
- reactjs - 如何修复 Firebase Cloud Functions 上的“Cannot GET”错误
- c# - WPF 在嵌套网格中动态设置控制列和行
- python - 无法理解如何运行 pyomo 脚本
- qt - Qmake 获取父目录
- flutter - 第一次出现在屏幕上时颤振 sharedpreferences 值显示 null
- java - 为什么我的应用程序在我重新运行时没有更新?
- passwords - 获取星星形式的密码