如何在Retrofit的多部分请求中发送对象数组

4
我想发送包含数组对象的多部分数据。我尝试过多种方法,但都无法正常工作。我的问题出在contributor参数上。服务器显示:需要contributor.0.id和contributor.0.role等其余列表中的项目。服务器读取到有一个contributor数组和其中有项,但由于某些原因无法提取它。请问有什么帮助吗?在Postman中如何工作(POST/form-data),我无法用Retrofit做同样的事情。
@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 : Serializable{

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

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

}


按照这个答案操作,你会得到结果。我已经尝试过了,对我有效。请查看Wasi Sadam的回答。 https://dev59.com/c1QK5IYBdhLWcg3wDLvP - Vasudev Vyas
4个回答

2

这是我唯一有效的方法。

首先创建一个哈希表,并按照以下方式映射我的数据:

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

当其中一个字段是图像时怎么办?contributors[?][image] = <IMG>你如何添加它? - TheRealChx101

0

你可以使用@partMap

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

0
把你的代码改成这样
            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
使用 @Field
@Field("contributors[]") contributors: MutableList<Contributor>

它说@Field参数只能与表单编码一起使用。 - Ahmed Abdeen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接