how to parse json array in android using volley

a 夏天 提交于 2020-02-24 05:30:31

问题


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();
                }
            }
        });

回答1:


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);


 }

}



回答2:


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"
        }
    ]
}



回答3:


You can achieve like this, try to use optJSONArray, optJSONObject and optString like that instead of get, Get will give exception but opt will give you null if you don't have that key.

    try {
        JSONObject responseObject = new JSONObject(response);


        JSONArray saveBookingArray = responseObject.optJSONArray("savebooking");

        if (saveBookingArray == null || saveBookingArray.length() == 0) {
            return;
        }

        for (int i = 0; i < saveBookingArray.length(); i++) {
            JSONObject bookingJsonObject = saveBookingArray.optJSONObject(i);

            if(bookingJsonObject == null) {
                continue;
            }

            String id = bookingJsonObject.optString("id");
            String contributorId = bookingJsonObject.optString("contributor_id");
            String tofId = bookingJsonObject.optString("table_of_content_id");
            String compositionId = bookingJsonObject.optString("composition_id");
            String completion = bookingJsonObject.optString("completion");
            String approved = bookingJsonObject.optString("approved");
            String cdnId = bookingJsonObject.optString("cdn_id");
            String secretToken = bookingJsonObject.optString("secret_token");
            String uploadedOn = bookingJsonObject.optString("uploaded_on");
            String created = bookingJsonObject.optString("created");
            String modified = bookingJsonObject.optString("modified");

            // You can create on Object and add it in list
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }



回答4:


try this my friend

read json data like this

        try{
        Booking myBooking= new Booking();
        //Here is main response object
        JSONObject json = new JSONObject(response);

        //now you have json array
        JSONArray booking = json.getJSONArray("savebooking");

       // now get your json array data
        if(booking.length ()> 0){

           for(int i=0;i<booking.length ();i++){
           //  now get you all data like this
               JSONObject bookingObject = booking.getJsonObject(i);
               myBooking.setId( bookingObject.getString("id"));
               myBooking.setContributor_id( bookingObject.getString("contributor_id"));

               list.addAll(myBooking);

           }

        }

    }catch (Exception e){
        Log.e("Error",e+"");
    }

create one model class like this.

public class Booking {

private String id;
private String  contributor_id;
private String  table_of_content_id;
private String  composition_id;
private String  completion;
private String  approved;
private String cdn_id ;
private String  secret_token;
private String  uploaded_on;
private String  created;
private String  modified;


public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getContributor_id() {
    return contributor_id;
}

public void setContributor_id(String contributor_id) {
    this.contributor_id = contributor_id;
}

public String getTable_of_content_id() {
    return table_of_content_id;
}

public void setTable_of_content_id(String table_of_content_id) {
    this.table_of_content_id = table_of_content_id;
}

public String getComposition_id() {
    return composition_id;
}

public void setComposition_id(String composition_id) {
    this.composition_id = composition_id;
}

public String getCompletion() {
    return completion;
}

public void setCompletion(String completion) {
    this.completion = completion;
}

public String getApproved() {
    return approved;
}

public void setApproved(String approved) {
    this.approved = approved;
}

public String getCdn_id() {
    return cdn_id;
}

public void setCdn_id(String cdn_id) {
    this.cdn_id = cdn_id;
}

public String getSecret_token() {
    return secret_token;
}

public void setSecret_token(String secret_token) {
    this.secret_token = secret_token;
}

public String getUploaded_on() {
    return uploaded_on;
}

public void setUploaded_on(String uploaded_on) {
    this.uploaded_on = uploaded_on;
}

public String getCreated() {
    return created;
}

public void setCreated(String created) {
    this.created = created;
}

public String getModified() {
    return modified;
}

public void setModified(String modified) {
    this.modified = modified;
}

}




回答5:


get json as model using this url

http://pojo.sodhanalibrary.com/

ArrayList<Booking> bookingeventModelList=new Arrayllist();
    JSONArray array=new JsonArray("savebooking")
    for(int i=0;i<array.size;i++)
    {
     Type listType = new TypeToken<List<Booking>>() {
                }.getType();
                bookingeventModelList= gson.fromJson(array.get(i), listType);
    }



回答6:


You can either go for GSON library which will parse JsonArray And add it to Model(POJO) or you can manually parse it.

for manual parsing you can try following code

StringRequest postStringRequest = new StringRequest(Request.Method.POST, BOOK_API, new Response.Listener() {

                @Override
                public void onResponse(String response) {
                    Log.d(TAG, "Response Check :" + response);

                    try {
             JSONObject json = new JSONObject(response);
JSONArray bookArray=json.getJSONArray("savebooking");
for (int i=0;i<bookArray.length();i++){
    JSONObject bookObject=bookArray.getJSONObject(i);
    String id = bookObject.optString("id");
    String contributor_id= bookObject.optString("contributor_id");
    String tbId = bookObject.optString("table_of_content_id");
    String compositionId = bookObject.optString("composition_id");
    String completion = bookObject.optString("completion");
    String approved = bookObject.optString("approved");
    String cdnId = bookObject.optString("cdn_id");
    String secretToken = bookObject.optString("secret_token");
    String uploadedOn = bookObject.optString("uploaded_on");
    String created = bookObject.optString("created");
    String modified = bookObject.optString("modified");

   list.add(new YourModelName(id,contributor_id,.....))   //all required parameters

}

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }


来源:https://stackoverflow.com/questions/44626934/how-to-parse-json-array-in-android-using-volley

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!