How to send array of objects in retrofit multipart request

倾然丶 夕夏残阳落幕 提交于 2021-01-27 13:42:13

问题


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.

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

}


回答1:


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



回答2:


Use @Field

@Field("contributors[]") contributors: MutableList<Contributor>



回答3:


You can use @partMap

@PartMap() Map<String, List<Contributor>> contibutors


来源:https://stackoverflow.com/questions/58949477/how-to-send-array-of-objects-in-retrofit-multipart-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!