Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse json array in android using volley

I am trying to fetch this JSON array but didn't get the result. Can someone please tell me how can I do using volley. I need all the data within the booking. Please help me to achieve it.

{
    "code": 200,
    "savebooking": [
        {
            "Booking": {
                "id": "304",
                "contributor_id": "16",
                "table_of_content_id": "6791",
                "composition_id": "7469",
                "completion": "2017-06-30",
                "approved": null,
                "cdn_id": "328301423",
                "secret_token": "s-riQMc",
                "uploaded_on": "2017-06-16 07:51:35",
                "created": "2017-06-16 07:48:31",
                "modified": "2017-06-16 07:51:35"
            }
        },
        {
            "Booking": {
                "id": "305",
                "contributor_id": "16",
                "table_of_content_id": "6791",
                "composition_id": "7470",
                "completion": "2017-06-30",
                "approved": null,
                "cdn_id": "328318377",
                "secret_token": "s-naSse",
                "uploaded_on": "2017-06-16 10:43:39",
                "created": "2017-06-16 07:48:31",
                "modified": "2017-06-16 10:43:39"
            }
        },
        {
            "Booking": {
                "id": "306",
                "contributor_id": "16",
                "table_of_content_id": "6791",
                "composition_id": "7471",
                "completion": "2017-06-30",
                "approved": null,
                "cdn_id": null,
                "secret_token": null,
                "uploaded_on": null,
                "created": "2017-06-16 07:48:31",
                "modified": "2017-06-16 07:48:31"
            }
        },
        {
            "Booking": {
                "id": "307",
                "contributor_id": "16",
                "table_of_content_id": "6791",
                "composition_id": "7472",
                "completion": "2017-06-30",
                "approved": null,
                "cdn_id": null,
                "secret_token": null,
                "uploaded_on": null,
                "created": "2017-06-16 07:48:31",
                "modified": "2017-06-16 07:48:31"
            }
        }
    ]
}

How can I parse this JSON response using volley? I have tried this but didn't get the result.

StringRequest postStringRequest = new StringRequest(Request.Method.POST, BOOK_API,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Response Check :" + response);
                try {
                    JSONObject json = new JSONObject(response);
                    JSONObject booking = json.getJSONArray("savebooking").getJSONObject("Booking");
                    Log.d(TAG, "booking Response Check :" + booking);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
like image 638
Dev Avatar asked Sep 12 '25 02:09

Dev


2 Answers

Here is

 //Here is main response object
JSONObject json = new JSONObject(response);

 //now get your  json array like this 
JSONArray booking = json.getJSONArray("savebooking");

// now check the array length > 0

if(booking.length ()> 0){

 for(int countItem = 0;countItem<booking.length;countItem++){

       JSONObject bookingObject = booking.getJsonObject(countItem);

       String id = bookingObject.isNull("id")?"":bookingObject.optString("id");
   list.add(id);


 }

}
like image 129
Vij Avatar answered Sep 13 '25 14:09

Vij


There are four steps you need to perform to get the data in POJO (Plain Old Java Object) format using Volley and Gson.

  1. Preparing the request object
  2. Invoking the API
  3. Catching the Response
  4. Parsing the Response

Preparing the request object:

You are preparing a nice StringRequest. However, since you are getting a JSON object as the response you should use JSONObjectRequest as follows.

JsonObjectRequest saveBookingsRequest = new JsonObjectRequest(BOOK_API, null, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        try {
            JSONArray saveBookings = response.getJSONArray("savebooking");
            Gson gson = new Gson();
            SaveBooking[] bookings = gson.fromJson(books, SaveBooking[].class);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, error.getMessage());
    }
});

Invoking the API:

To invoke the prepared request you need a RequestQueue. And, you must add the prepared request to the queue.

RequestQueue queue = Volley.newRequestQueue(this);

// Add the request to the RequestQueue.
queue.add(saveBookingsRequest);

Catching the Response:

This code we already wrote while preparing the Request. We catch response by overriding onResponse() method of Response.Listener. In here, we are extracting savebooking JSONArray from response object.

@Override
public void onResponse(JSONObject response) {
    try {
        JSONArray saveBookings = response.getJSONArray("savebooking");
        Gson gson = new Gson();
        SaveBooking[] bookings = gson.fromJson(books, SaveBooking[].class);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Parsing the Response:

Finally, you need to parse from JSON to POJO. The best library to use for JSON parsing is Gson. For that, you need to create a Booking class and a wrapper SaveBooking class.

Booking:

public class Booking {

    @SerializedName("id")
    public int mId;

    @SerializedName("contributor_id")
    public int mContributorId;

    @SerializedName("table_of_content_id")
    public int mTableOfContentId;

    @SerializedName("composition_id")
    public int mCompositionId;

    @SerializedName("completion")
    public String completion;

    @SerializedName("approved")
    public Object mApproved;

    @SerializedName("cdn_id")
    public int mCdnId;

    @SerializedName("secret_token")
    public String mSecretToken;

    @SerializedName("uploaded_on")
    public String mUploadedOn;

    @SerializedName("created")
    public String mCreated;

    @SerializedName("modified")
    public String mModified;    
}

SaveBooking:

public class SaveBooking {
    @SerializedName("Booking")
    public Booking booking;
}

And then in onResponse() you need to parse the JSON string to an Array of Booking objects:

Gson gson = new Gson();
SaveBooking[] bookings = gson.fromJson(books, SaveBooking[].class);

Assumptions/Limitations:

  1. Booking.approved is of type Object because all values of approved are null.
  2. All Date or DateTime fields are stored as String.
  3. If you only want Booking class then you should change the response to remove SaveBooking wrapper from the JSON response.

In that case, your savebooking will look like:

{
    "savebooking": [
        {
            "id": "304",
            "contributor_id": "16",
            "table_of_content_id": "6791",
            "composition_id": "7469",
            "completion": "2017-06-30",
            "approved": null,
            "cdn_id": "328301423",
            "secret_token": "s-riQMc",
            "uploaded_on": "2017-06-16 07:51:35",
            "created": "2017-06-16 07:48:31",
            "modified": "2017-06-16 07:51:35"
        },
        {
            "id": "305",
            "contributor_id": "16",
            "table_of_content_id": "6791",
            "composition_id": "7470",
            "completion": "2017-06-30",
            "approved": null,
            "cdn_id": "328318377",
            "secret_token": "s-naSse",
            "uploaded_on": "2017-06-16 10:43:39",
            "created": "2017-06-16 07:48:31",
            "modified": "2017-06-16 10:43:39"
        }
    ]
}
like image 20
BhalchandraSW Avatar answered Sep 13 '25 15:09

BhalchandraSW