ANDROID : How to use org.json.JSONArray in for loop

I use library JsonHttpResponseHandler and this my code

Data JSON is =

[{"id":"4","2":"123","phone":"123","1":"Shin","0":"4","name":"Shin"},{"id":"5","2":"555","phone":"555","1":"Wolf","0":"5","name":"Wolf"},{"id":"6","2":"666","phone":"666","1":"Lunar","0":"6","name":"Lunar"}]

And this my code =

@Override
        public void onSuccess(int statusCode, org.apache.http.Header[] headers, org.json.JSONArray response)

Question is how can i use response data in for loop

Upvotes: 0

Views: 252

Answers (3)

Jatin
Jatin

Reputation: 1670

Use below code ,

for (int i = 0; i < response.length(); i++) {
        try {
            JSONObject jobj = response.getJSONObject(i);

            String id = jobj.getString("id");
            String two = jobj.getInt("2");
            String phone = jobj.getInt("phone");
            String one = jobj.getInt("1");
            String zero = jobj.getInt("0");
            String name = jobj.getString("name");

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

Upvotes: 1

Patato
Patato

Reputation: 1472

String dataStr="[{\"id\":\"4\",\"2\":\"123\",\"phone\":\"123\",\"1\":\"Shin\",\"0\":\"4\",\"name\":\"Shin\"},{\"id\":\"5\",\"2\":\"555\",\"phone\":\"555\",\"1\":\"Wolf\",\"0\":\"5\",\"name\":\"Wolf\"},{\"id\":\"6\",\"2\":\"666\",\"phone\":\"666\",\"1\":\"Lunar\",\"0\":\"6\",\"name\":\"Lunar\"}]";


    try {
        JSONArray jsonStrs =new JSONArray("1111");
        for(int i=0;i<jsonStrs.length();i++)
        {
            JSONObject jobj=jsonStrs.getJSONObject(i);
            int id=jobj.getInt("id");
            String phone=jobj.getString("phone");
            //get other values 
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Upvotes: 0

Ker p pag
Ker p pag

Reputation: 1588

it is the same as array.

for(int i =0 ; i < response.length() ; i++){

JSONObject object = response.getJSONObject(i);

}

inside json array > jsonobject it is like using a List

for your reference : JSON Array iteration in Android/Java

Upvotes: 0

Related Questions