Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send json array in android retrofit?

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}}]}
like image 335
Thae Thae Avatar asked Jan 27 '23 02:01

Thae Thae


1 Answers

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.

like image 158
Viswas Kg Avatar answered Jan 28 '23 17:01

Viswas Kg