gpt4 book ai didi

java - 从 JSONArray 中提取字符串

转载 作者:行者123 更新时间:2023-11-30 01:56:46 45 4
gpt4 key购买 nike

我正在尝试构建一个有趣的测验游戏,但我正在努力弄清楚如何从 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");”的行

最佳答案

您需要使用在循环中声明的i:

  mQuestion = arr.getJSONObject(i).getString("question");

关于java - 从 JSONArray 中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54184163/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com