如何使用volley

时间:2017-06-19 09:33:21

标签: android json android-volley

我正在尝试获取此JSON数组,但没有得到结果。有人可以告诉我怎么用截击。我需要预订中的所有数据。请帮助我实现它。

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

如何使用volley解析此JSON响应? 我试过这个,但没有得到结果。

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

6 个答案:

答案 0 :(得分:1)

这是

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

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

//现在检查数组长度&gt; 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);


 }

}

答案 1 :(得分:1)

使用Volley和Gson以POJO(普通旧Java对象)格式获取数据需要执行四个步骤。

  1. 准备请求对象
  2. 调用API
  3. 抓住回应
  4. 解析回应
  5. 准备请求对象:

    你正在准备一个不错的StringRequest。但是,由于您要获取JSON对象作为响应,因此应使用JSONObjectRequest,如下所示。

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

    调用API:

    要调用准备好的请求,您需要RequestQueue。而且,您必须将准备好的请求添加到队列中。

    RequestQueue queue = Volley.newRequestQueue(this);
    
    // Add the request to the RequestQueue.
    queue.add(saveBookingsRequest);
    

    抓住回复:

    我们在准备请求时已编写此代码。我们通过覆盖onResponse() Response.Listener方法来捕获响应。在这里,我们从savebooking对象中提取response JSONArray。

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

    解析响应:

    最后,您需要从JSON解析为POJO。用于JSON解析的最佳库是Gson。为此,您需要创建一个Booking类和一个包装器SaveBooking类。

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

    然后在onResponse()中,您需要将JSON字符串解析为Booking个对象数组:

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

    <强>假设/限制:

    1. Booking.approved的类型为Object,因为所有已批准的值都为null。
    2. 所有DateDateTime字段都存储为String
    3. 如果您只想要Booking类,那么您应该更改响应以从JSON响应中删除SaveBooking包装。
    4. 在这种情况下,您的savebooking将如下所示:

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

答案 2 :(得分:0)

使用此网址将json作为模型

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

答案 3 :(得分:0)

试试这个我的朋友

像这样读取json数据

        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+"");
    }

像这样创建一个模型类

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

}

答案 4 :(得分:0)

你可以这样实现,尝试使用optJSONArray,optJSONObject和optString,而不是get,Get会给出异常但是如果你没有那个键,opt会给你null。

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

答案 5 :(得分:0)

您可以选择将解析JsonArray的GSON库并将其添加到Model(POJO)中,也可以手动解析它。

对于手动解析,您可以尝试以下代码

StringRequest postStringRequest = new StringRequest(Request.Method.POST,BOOK_API,                 新的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();
                    }

                }