2017-12-27 122 views
1

我想在我的代碼中使用Volley哪些請求類型應該用於我的響應下面我無法理解。 URL ::: http://localhost/api/product/read.php排球JSON響應

{ 
     "data":[ 
     { 
     "category_id":"1", 
     "category_name":"Today's Recipe", 
     "recipes":[ 
      { 
      "id":"1", 
      "recipe_name":"Peanut, and Chilli Noodles", 
      "ingredients":"Serves: 4 \r\n\r\n250g (9 oz) fresh Chinese , 
      "prepration":"Prep:15min Cook:10min Ready in:25min \r\n\r\nCook 
      noodles in a large pot of boiling water until done. have 
      chilli paste, use minced red chilli to taste." 
    } 
    ] 
    }, 
+0

這似乎是一個JSON對象,所以你應該使用一個JsonObjectRequest https://developer.android.com/training/volley/request.html – joao86

+0

你應該使用JsonRequest。請參閱我在本博客上的回答: https://stackoverflow.com/questions/47936955/i-am-unable-to-make-a-network-call-using-volley-i-have-tried-many-solutions -but/47937120#47937120 –

+0

當我使用jsonobject請求時,出現以下錯誤顯示::: com.android.volley.ParseError:org.json.JSONException:值java.lang.String類型的連接無法轉換爲JSONObject –

回答

0

試試這個:

RequestQueue requestQueue = Volley.newRequestQueue(context); 
    final String url = "url here"; 

    JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null, 
      new Response.Listener<JSONObject>() 
      { 
       @Override 
       public void onResponse(JSONObject response) 
       { 
       Log.e(" result",(String.valueOf(response))); 
       } 
      }, 
      new Response.ErrorListener() 
      { 
       @Override 
       public void onErrorResponse(VolleyError error) { 

       } 
      } 
    ); 
    requestQueue.add(getRequest); 

希望這有助於。

+0

我也試過了,但它顯示字符串請求無法轉換爲Json對象 –

+0

看看這個https://stackoverflow.com/questions/17992753/can-not-convert-json-string-to-object – nimi0112

0
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { 
      @Override 
      public void onResponse(String response) { 

       if (response != null) { 
        try { 
JSONObject jsonObject = new JSONObject(response); 
         if (jsonObject.getString("status").equalsIgnoreCase("success")) { 
        JSONArray jsonArray = jsonObject.getJSONArray("data"); 
if(jsonArray!=null && jsonArray.length()>0){ 
    for(int i=0;i<jsonArray.length();i++){ 
JSONObject data_object=jsonArray.getJSONObject(i); 
JSONArray recepie = data_object.getJSONArray("recipes"); 

} 
//       
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       } 

     }); 
     MySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest); 
     jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
       APIConstants.API_TIMEOUT, //for 30 Seconds 
       DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
       DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); 
    } 

希望這有助於