2016-04-14 24 views
0

工作,我嘗試使用郵差,它的工作原理完全沒JSONArray後無法從Android應用

Postman Screenshot

但是,當我從應用程序後,只有表和成本對象被公佈。

這裏是我的Android代碼

JSONObject sendObj = null; 

      sendObj = new JSONObject(); 
      try { 
       sendObj.put("table",mTableUser); 
       sendObj.put("cost",cost); 

       for(int i=0;i<mOrderFoodList.size();i++) { 

        sendObj.put("serve["+i+"][food]",mOrderFoodList.get(i).getID()); 
        sendObj.put("serve["+i+"][number]",mOrderFoodList.get(i).getQuantity()); 
        sendObj.put("serve["+i+"][status]", 0); 

       } 


      }catch (JSONException e) { 
       e.printStackTrace(); 
      } 
mVolleyService.postDataVolley("POSTCALL", mConstants.BASE_URL +mConstants.ORDER, sendObj); 

這是Android應用程序

{ 
"_id": "570fc02422ed0203002723d2", 
"cost": 60, 
"table": 1, 
"__v": 0, 
"serve": [] 
} 

從郵差輸出,

{ 
"_id": "570faed422ed0203002723c8", 
"cost": 200, 
"table": 20, 
"__v": 0, 
"serve": [ 
    { 
    "food": "56fac73f284ea80300ba6b42", 
    "quan": 4, 
    "status": 0, 
    "_id": "570faed422ed0203002723c9" 
    }, 
    { 
    "food": "56fac6d0284ea80300ba6b41", 
    "quan": 3, 
    "status": 0, 
    "_id": "570faed422ed0203002723ca" 
    } 
] 
} 

此功能用於發佈

public void postDataVolley(final String requestType, String url,JSONObject sendObj){ 
    try { 
     queue = Volley.newRequestQueue(mContext); 

     JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 
       if(mResultCallback != null) 
        mResultCallback.notifySuccess(requestType,response); 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       if(mResultCallback != null) 
        mResultCallback.notifyError(requestType,error); 
      } 

     }) 
     { 
      @Override 
      public Map<String, String> getHeaders() throws AuthFailureError { 
       HashMap<String, String> headers = new HashMap<>(); 
       headers.put("x-access-token", token); 


       return headers; 
      } 



     }; 

     queue.add(jsonObj); 

    }catch(Exception e){ 

    } 
} 

我在發送JSONObject時犯了什麼錯誤?

+1

也許mOrderFoodList是空的? – Pooya

+0

不,我檢查日誌,它不是空的:( – MrRobot9

+0

@ArjunHegde你可以顯示用於發送數據的完整代碼? –

回答

0

您需要爲serve創建JSONArray。爲每個發球創建一個JSONObject並將其放入JSONArray

試試這個代碼,

JSONObject sendObj = new JSONObject(); 
try { 
    sendObj.put("table",mTableUser); 
    sendObj.put("cost",cost); 

    JSONArray serveArray = new JSONArray(); 
    for(int i=0; i<mOrderFoodList.size(); i++) { 
     JSONObject singleServe = new JSONObject(); 
     singleServe.put("food",mOrderFoodList.get(i).getID()); 
     singleServe.put("number",mOrderFoodList.get(i).getQuantity()); 
     singleServe.put("status", 0); 
     serveArray.putJSONObject(singleServe); 
    } 
    sendObj.putJSONArray(serveArray); 

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