我正在尝试从JSON读取数据。我将Firebase添加到我的Android应用程序中,并且一切正常,但是我不明白如何读取数组字段。
例如,我需要获取"correctAnswers":["Var1","Var4"]
字段,但Google无法回答如何做到。
请解释。 谢谢。
我的JSON文件的一部分
{
"answA" : "Var1",
"answB" : "Var2",
"answC" : "Var3",
"answD" : "Var4",
"categoryId" : 1,
"correctAnswers":["Var1","Var4"],
"id" : 104,
}
我得到了光标
Cursor cursor = sqlLiteDataBaseInstance.rawQuery(String.format("SELECT * FROM Question WHERE CategoryID = %d ORDER BY RANDOM() LIMIT 30", category), null);
并可以使用
读取answA, answB, answC, answD
cursor.getString(cursor.getColumnIndex(String columnName))
和
categoryId, id using cursor.getInt(cursor.getColumnIndex(String columnName))
答案 0 :(得分:0)
检查。
private void readJson() {
try {
JSONObject jsonObject = new JSONObject("{\n" +
"\t\"answA\": \"Var1\",\n" +
"\t\"answB\": \"Var2\",\n" +
"\t\"answC\": \"Var3\",\n" +
"\t\"answD\": \"Var4\",\n" +
"\t\"categoryId\": 1,\n" +
"\t\"correctAnswers\": [\"Var1\", \"Var4\"],\n" +
"\t\"id\": 104\n" +
"}");
JSONArray jsonArray = jsonObject.getJSONArray("correctAnswers");
Log.e("Array Size is ", jsonArray.length() + "");
for (int i = 0; i < jsonArray.length(); i++) {
Log.e("Array Values", jsonArray.getString(i) + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}