Search code examples
androidkotlinretrofitrx-java

How to send array of objects in retrofit multipart request


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 = ""

}


Solution

  • 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>>