I am trying to read data from JSON. I add Firebase to my Android application and everyhing works fine, but i don't understand how to read array fields.
For example, I need to get "correctAnswers":["Var1","Var4"]
field, but can't google answer how to do it.
Please explain. Thank you.
part of my JSON file
{
"answA" : "Var1",
"answB" : "Var2",
"answC" : "Var3",
"answD" : "Var4",
"categoryId" : 1,
"correctAnswers":["Var1","Var4"],
"id" : 104,
}
I get the cursor
Cursor cursor = sqlLiteDataBaseInstance.rawQuery(String.format("SELECT * FROM Question WHERE CategoryID = %d ORDER BY RANDOM() LIMIT 30", category), null);
and can read answA, answB, answC, answD
using
cursor.getString(cursor.getColumnIndex(String columnName))
and
categoryId, id using cursor.getInt(cursor.getColumnIndex(String columnName))
Check this.
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();
}
}