How To Retrieve Sub-array Of An Array In Json Through Api Using Volley In Android?
JSON api file: { 'state': 'Jammu and Kashmir', 'statecode': 'JK', 'districtData': [ { 'district': 'Anantnag', 'notes': '', 'active': 107
Solution 1:
STRUCTURE
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, "https://api.covid19india.org/v2/state_district_wise.json",null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject dataOBJ = response.getJSONObject(i);
JSONArray jsonChild = dataOBJ.getJSONArray("districtData");
for (int k = 0; k < jsonChild.length(); k++) {
JSONObject obj = jsonChild.getJSONObject(k);
int active = obj.getInt("active");
String district = obj.getString("district");
JSONObject child = obj.getJSONObject("delta");
int confirmed = child.getInt("confirmed");
}
}
} catch (Exception exp) {
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
Solution 2:
Try this way
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"https://api.covid19india.org/v2/state_district_wise.json",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "onResponse: "+response);
try {
JSONArray responseArray = new JSONArray(response);
for (int i = 0; i < responseArray.length(); i++) {
JSONObject stateObject = responseArray.getJSONObject(i);
JSONArray districtArray = stateObject.getJSONArray("districtData");
for(int j=0; j<districtArray.length(); j++){
JSONObject districtObject = districtArray.getJSONObject(j);
//do what you want to do with district object
Log.d(TAG, "onResponse: "+districtObject.toString());
}
}
}catch (JSONException e){
Log.d(TAG, "onResponse: "+e.getMessage());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Post a Comment for "How To Retrieve Sub-array Of An Array In Json Through Api Using Volley In Android?"