0

I am trying to get the data from the below JSON output. I am unable to get the data using the below mentioned java code. Could you please help me to correct my code ?

[
  {
"id": "bitcoin",
"symbol": "btc",
"name": "Bitcoin", 
  }
]

Code

public void loadAltCoins(String result) {

    try {
        JSONObject reader = new JSONObject(result);
        JSONArray jArray = new JSONArray(reader);

        for (int i = 0; i < jArray.length(); i++) {
            json_data = jArray.getJSONObject(i);
            System.out.println("Testing ID : " + json_data.getString("id"));
        }
}
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
iappmaker
  • 2,945
  • 9
  • 35
  • 76

1 Answers1

4

You don't need to create a JSONObject({}) for JSONArray ([]) so use

//JSONObject reader = new JSONObject(result); not required
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
     json_data = jArray.getJSONObject(i);
     System.out.println("Testing ID : " + json_data.optString("id"));
}// use optString, no exception and auto parsing
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68