问题
I can't send json array to server. When I test in postman raw, it is ok, success return.
Postman Raw;
[
{
"product_id": 2,
"name": "Umbrella",
"price": 200,
"quantity": 1,
"totalprice": 200,
"user_id": 1
},
{
"product_id": 1,
"name": "Apple",
"price": 200,
"quantity": 1,
"totalprice": 200,
"user_id": 1
}
]
APIInterface;
@POST("example/api/order")
Call<JSONArray> postOrder(@Body JSONArray jsonArray);
CartActivity;
try {
JSONArray jsonArray = new JSONArray();
for (Cart cart : cartList) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("product_id", cart.getProduct_id());
jsonObject.put("name", cart.getName());
jsonObject.put("price", cart.getPrice());
jsonObject.put("quantity", cart.getQuantity());
jsonObject.put("totalprice", cart.getTotalprice());
jsonObject.put("user_id", cart.getUser_id());
jsonArray.put(jsonObject);
}
Log.e("JSONArray", String.valueOf(jsonArray));
} catch (JSONException jse) {
jse.printStackTrace();
}
Log;
E/JSONArray: [{"product_id":1,"name":"Umbrella","price":200,"quantity":1,"totalprice":200,"user_id":1},{"product_id":2,"name":"Apple","price":89,"quantity":1,"totalprice":89,"user_id":1}]
Error Message from server;
{"values":[{"nameValuePairs":{"product_id":1,"name":"Umbrella","price":200,"quantity":1,"totalprice":200,"user_id":1}},{"nameValuePairs":{"product_id":2,"name":"Apple","price":89,"quantity":1,"totalprice":89,"user_id":1}}]}
回答1:
You can directly send the array of objects as parameter. Retrofit will handle the conversion. Change your interface method like this:
@POST("example/api/order")
Call<JSONArray> postOrder(@Body List<Cart> cartList);
Check this link, you will get an idea.
回答2:
send like this:-
@POST("example/api/order")
Call<JSONArray> postOrder(@Query ("data") JSONArray jsonArray);
来源:https://stackoverflow.com/questions/56981910/how-to-send-json-array-in-android-retrofit