I am trying to get all values from an array, which are placed in JSON.
This is my JSON:
{
"greetings": [
"Hello",
"Hi",
"Hey"
]
}
try {
JSONObject json = new JSONObject(Objects.requireNonNull(Helper.loadJSONFromAsset(getApplicationContext()))); // Returns a JSON string
JSONArray who = json.getJSONArray(intent);
for (int i = 0; i < who.length(); i++) {
System.out.println(who.getJSONObject(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
public static String loadJSONFromAsset(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("speech.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, StandardCharsets.UTF_8);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
I get this error:
W/System.err: org.json.JSONException: Value Hello at 0 of type
java.lang.String cannot be converted to JSONObject
What’s wrong with my code?
>Solution :
The array contains Strings, not JSONObjects. Therefore,
System.out.println(who.getString(i));