android - 如何在 retrofit 多部分请求中发送对象数组

标签 android kotlin retrofit rx-java

我想发送包含多部分数据的数组对象。我尝试了很多方法,但没有用。我的贡献者参数问题。服务器说。 contributor.0.id 是必需的 & contributor.0.role 是必需的,依此类推列表中的其余项目。服务器读到有一个贡献者数组并且它有项目但由于某种原因他无法提取它。 Here is how it works on postman (POST/form-data) I can't do the same with 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)贡献者

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/

相关文章:

java - 从 Java/Kotlin 中启动的进程中获取 InputStream

android - Kotlin - 将数据从 Activity 发送回 fragment

android - 如何为 Retrofit 配置调试和发布日志级别?

java - 如何使用 Retrofit 2 和 Android Studio 获取 JSON 对象?

php - 我的 .php/?PHPSESSID=xxxxxxxxxxxxxxxxxx 出现意外响应代码 500

android - 如何在 Kotlin 的 fragment 内使用按钮在 fragment 之间切换?

Android:翻译动画和相对布局

android - RxJava 2 Retrofit 和动态 url 以及 @url 注释

android - 如何在 Toast 通知中包含按钮?

Android SurfaceView 预览太暗