Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get array values from JSON?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading