how to send json array in android retrofit?

穿精又带淫゛_ 提交于 2021-02-10 12:12:57

问题


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

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