【发布时间】:2019-06-08 14:20:39
【问题描述】:
我正在尝试构建一个有趣的测验游戏,但我正在努力弄清楚如何从 Android Studio 中的 JSONArray 中提取我想要的字符串
我在 Logcat 中获得了“JSON”和“结果”的日志,但我似乎无法弄清楚如何将我的 mQuestion 变量设置为相关字符串。
JSON
{
"response_code":0,
"results":[{
"category":"General Knowledge",
"type":"multiple",
"difficulty":"medium",
"question":"According to the BBPA, what is the most common pub name in the UK?",
"correct_answer":"Red Lion",
"incorrect_answers": [
"Royal Oak",
"White Hart",
"King's Head"
]
}]
}
我的代码
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("JSON", s);
try {
JSONObject jsonObject = new JSONObject(s);
String results = jsonObject.getString("results");
Log.i("results", results);
JSONArray arr = new JSONArray(results);
for (int i = 0; i < arr.length(); i++) {
mQuestion = arr.getJSONObject(3).getString("question");
Log.i("Question", mQuestion);
}
} catch (Exception e) {
e.printStackTrace();
}
}
我得到的 Logcat 是 W/System.err: at ...MainActivity$getQuestion.onPostExecute(MainActivity.java:67)
67 是包含 "mQuestion = arr.getJSONObject(3).getString("question");" 的行
【问题讨论】:
标签: java json android-studio