如何在android改造中发送json数组?

时间:2019-07-11 05:02:07

标签: android json retrofit2

我无法将json数组发送到服务器。当我用邮递员原始测试时,可以,成功返回。

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();
}

日志;

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}]

来自服务器的错误消息;

{"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}}]}

2 个答案:

答案 0 :(得分:0)

像这样发送:-

@POST("example/api/order")
Call<JSONArray> postOrder(@Query ("data") JSONArray jsonArray);

答案 1 :(得分:0)

您可以直接发送对象数组作为参数。改装将处理转换。像这样更改您的接口方法:

@POST("example/api/order")
Call<JSONArray> postOrder(@Body List<Cart> cartList);

选中此link,您将获得一个想法。