Davinho Davinho - 1 year ago 81
Android Question

How to parse JsonArray values in Android

I would like to parse all name and id attribute from the following JSon Array:
JSon link

I tried with the following code but not working. I get

org.json.JSONException: Value [{"id":0,"name":"Alsópetény"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject


My code :

JSONArray jsonarray = new JSONArray(jsonList);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String id= jsonobject.getString("id");
String name= jsonobject.getString("name");


Answer Source

Yours (as I can see from the link you've posted) is a single JSON message {...} wich contains many nodes ("A","B", "E", "F"... and so on). Every node is a JSON Array wich contains some JSON Objects.

You must Get first the JSON Objects: "A", "B",... this way:

String result = EntityUtils.toString(response.getEntity()); //the result of HTTP call
JSONObject JO = new JSONObject(result);
JSONArray ja = JO.getJSONArray("A");
JSONArray jb = JO.getJSONArray("B");

Then you must access to the JsonArray elements:

for(int i=0; i< ja.length(); i++){
    JSONObject jo = ja.getJSONObject(i);
    String id = jo.getString("id");
    String name = jo.getString("name");

    System.out.println("id: " + id + "");
    System.out.println("name: " + name + "");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download