4

I want to send array objects with multipart data. I tried many ways but it is not working. My issue with the contributor parameter. Server says. contributor.0.id is required & contributor.0.role is required and so on for remaining items in the list. Server reads that there is a contributor array and it has items but he can't extract it for some reason.Here is how it works on postman (POST/form-data) I can't do the same with retrofit.

Any help please?

@Multipart
@POST("project/create")
fun createProject(
    @Header("Authorization") token: String,
    @Part("title") title: String,
    @Part img: MultipartBody.Part,
    @Part("release_date") releaseDate: String,
    @Part("contributors[]") contributors: MutableList<Contributor>
): Single<Response<String>>

Class Contributor

class Contributor : Serializable{

@SerializedName("id")
@Expose
var id: Int = 0

@SerializedName("role")
@Expose
var role: String = ""

}

Ahmed Abdeen
  • 325
  • 5
  • 14
  • follow this answer you will get result. I did it and it works for me. check wasi Sadam answer https://stackoverflow.com/questions/52553210/retrofit-2-multipart-image-upload-with-data – Vasudev Vyas Nov 20 '19 at 09:42

4 Answers4

2

Here is the only way worked for me.

First Created Hashmap and mapped my data on this way

val contributorsMap: HashMap<String, String> = HashMap()

    for((index, contributor) in contributorList.withIndex()){

        contributorsMap["contributors[${index}][id]"] = "${contributor.id}"
        contributorsMap["contributors[${index}][role]"] = contributor.role

    }

Then updated my function parameter to @PartMap instead

@Multipart
@POST("project/create")
fun createProject(
    @Header("Authorization") token: String,
    @Part("title") title: String,
    @Part img: MultipartBody.Part,
    @Part("release_date") releaseDate: String,
    @PartMap contributors: HashMap<String, String>,
): Single<Response<String>>
Ahmed Abdeen
  • 325
  • 5
  • 14
0

You can use @partMap

@PartMap() Map<String, List<Contributor>> contibutors
AkashToSky
  • 107
  • 1
  • 11
0

change your code like this

            val contributorsMap: HashMap<String, RequestBody> = HashMap()

            for((index, contributor) in parts.withIndex()){

                contributorsMap["contributors[${index}][id]"] = contributor.id.toString().toRequestBody("text/plain".toMediaType())
                contributorsMap["contributors[${index}][role]"] = contributor.role.toRequestBody("text/plain".toMediaType())

            }
-1

Use @Field

@Field("contributors[]") contributors: MutableList<Contributor>
sasikumar
  • 12,540
  • 3
  • 28
  • 48