如何在改装多部分请求中发送对象数组

How to send array of objects in retrofit multipart request

我想发送包含多部分数据的数组对象。我尝试了很多方法,但没有用。我的贡献者参数问题。服务器说。 contributor.0.id 是必需的 & contributor.0.role 是必需的,依此类推列表中的剩余项目。服务器读到有一个贡献者数组,它有项目,但由于某种原因他不能提取它。

有什么帮助吗?

@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 贡献者

class Contributor : Serializable{

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

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

}

使用@Field

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

你可以使用@partMap

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

这是对我有用的唯一方法。

首先创建 Hashmap 并以此方式映射我的数据

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

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

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

    }

然后将我的函数参数更新为@PartMap

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