我想发送包含多部分数据的数组对象。我尝试了很多方法,但没有用。我的贡献者参数问题。服务器说。 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 = ""
最佳答案
这是对我有用的唯一方法。
首先创建 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>>
关于android - 如何在 retrofit 多部分请求中发送对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58949477/