我正在尝试构建一个趣味测验游戏,但我正在努力寻找如何从Android Studio中的JSONArray中提取所需的字符串
我在Logcat中出现了“ JSON”和“结果”的日志,但是我似乎无法弄清楚如何将mQuestion变量设置为相关的字符串。
JSON
myView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
float y = event.getY();
float x = event.getX();
//Using the xy coordinates I want the height of the touch in the view
return false;
}
});
我的代码
{
"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"
]
}]
}
我进入的Logcat是W / System.err:位于... MainActivity $ getQuestion.onPostExecute(MainActivity.java:67)
67是包含“ mQuestion = arr.getJSONObject(3).getString(“ question”);“
的行答案 0 :(得分:2)
您需要使用在循环中声明的i
:
mQuestion = arr.getJSONObject(i).getString("question");
答案 1 :(得分:0)
您错误地解析了JsonObject和JsonArray。 使用此代码:
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("JSON", s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray results = jsonObject.getJSONArray("results");
JSONObject jsonObject1 = results.getJSONObject(0);
Log.i("results", results.toString());
String mQuestion = jsonObject1.getString("question");
Log.i("Question", mQuestion);
} catch (Exception e) {
e.printStackTrace();
}
}