【问题标题】:How to send array of objects in retrofit multipart request如何在改造多部分请求中发送对象数组
【发布时间】:2020-03-15 21:12:21
【问题描述】:

我想发送包含多部分数据的数组对象。我尝试了很多方法,但它不起作用。我对贡献者参数的问题。服务器说。对于列表中的其余项目,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 Contributor : Serializable{

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

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

}

【问题讨论】:

标签: android kotlin retrofit rx-java


【解决方案1】:

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

首先创建 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>>

【讨论】:

    【解决方案2】:

    你可以使用@partMap

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

    【讨论】:

      【解决方案3】:

      使用@Field

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

      【讨论】:

      • 它说@Field参数只能与表单编码一起使用
      猜你喜欢
      • 1970-01-01
      • 2015-10-16
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 2022-01-15
      • 2020-07-02
      • 1970-01-01
      相关资源
      最近更新 更多