如何通过改装使用addFormDataPart发送对象的数组列表?

时间:2019-11-08 16:54:22

标签: android kotlin retrofit

我有这样的请求主体,它包含对象数组

{
    "api_token" : "1572370159",
    "latt":29.970245729247,
    "lang": 31.14269679235,
    "patient_id":1,
    "insurance" : 0,
    "delivery" : 0,
    "notes": "notes",
    "photo": "",
    "orderDetails": [

        {"medicine_id": 1, "medicine_type_id": 1, "amount": 2},
        {"medicine_id": 1, "medicine_type_id": 1, "amount": 2},
        {"medicine_id": 1, "medicine_type_id": 1, "amount": 2},
        {"medicine_id": 1, "medicine_type_id": 1, "amount": 2},
        {"medicine_id": 1, "medicine_type_id": 1, "amount": 2},
        {"medicine_id": 1, "medicine_type_id": 1, "amount": 2},
        {"medicine_id": 1, "medicine_type_id": 1, "amount": 2},
        {"medicine_id": 1, "medicine_type_id": 1, "amount": 2},
        {"medicine_id": 1, "medicine_type_id": 1, "amount": 2},
        {"medicine_id": 2, "medicine_type_id": 2, "amount": 1}
    ]
}

如果我不发送订单,一切都很好 所以我怎么寄 这是我的代码:

我的终点

@POST("pharmacy/order/create")
    fun createPharmacyOrder(@Body requestBody: RequestBody)
            : Call<PharmacyOrderResponse>

这是尝试使用addFormDataPart发送此列表的代码

fun createPharmacyOrder(request :MedicineOrderRequest, callback: BaseResponseListener<PharmacyOrderResponse>) {
        val builder = MultipartBody.Builder()
        builder.setType(MultipartBody.FORM)
        builder.addFormDataPart("api_token" , request.api_token)
        builder.addFormDataPart("latt" , request.latt.toString())
        builder.addFormDataPart("lang" , request.lang.toString())
        builder.addFormDataPart("patient_id" , request.patient_id.toString())
        builder.addFormDataPart("insurance" , request.insurance.toString())
        builder.addFormDataPart("delivery" , request.delivery.toString())
        builder.addFormDataPart("notes" , request.notes)
        //request.orderDetails: ArrayList<OrderDetail>
        if (request.orderDetails.size > 0)
                builder.addFormDataPart("orderDetails"
                    , Gson().toJson(request.orderDetails)
                )

        if (!request.photo.equals("")) {
            with(File(request.photo)){
                builder.addPart(MultipartBody.Part.createFormData("photo",name
                , RequestBody.create(MediaType.parse("image/*"),this)))
            }
        }

        val service = ApiConfigure.mainRetrofit.create(ApiEndPoint::class.java)
        val call: Call<PharmacyOrderResponse> = service.createPharmacyOrder(builder.build())
        call.start(callback)
    }

1 个答案:

答案 0 :(得分:0)

请尝试在键中使用[]。 像这样:

builder.addFormDataPart(“ orderDetails []”,Gson()。toJson(request.orderDetails))