Home » Java » How to get JSON Array Java-Exceptionshub

How to get JSON Array Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment


I have code to get JSON Object but now I need to get a JSON Array.

JSONObject jData = new JSONObject(data);
        JSONObject rates = jData.getJSONObject("page");
        JSONArray namesArray = rates.names();
        for (int i = 0; i < namesArray.length(); i++) {
            String currency = namesArray.getString(i);
            String rate = rates.getString(currency);
            stringBuilder.append(String.format("%s: %s\n", currency, rate));
How to&Answers:

You can do like

 java.lang.Object optionWraper = data.get(key);
            JSONArray jarray = new JSONArray();
            if (optionWraper instanceof JSONArray) {
                jarray = (JSONArray) optionWraper;
             } else if (optionWraper instanceof JSONObject) {
              jarray.put((JSONObject) optionWraper);

You can parse the input object in either case JSONObject or JSONArray and don’t need to worry about the type in runtime .