问题
I want to send array objects with multipart data. I tried many ways but it is not working. My issue with the contributor parameter. Server says. contributor.0.id is required & contributor.0.role is required and so on for remaining items in the list. Server reads that there is a contributor array and it has items but he can't extract it for some reason.
Any help please?
@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
class Contributor : Serializable{
@SerializedName("id")
@Expose
var id: Int = 0
@SerializedName("role")
@Expose
var role: String = ""
}
回答1:
Here is the only way worked for me.
First Created Hashmap and mapped my data on this way
val contributorsMap: HashMap<String, String> = HashMap()
for((index, contributor) in contributorList.withIndex()){
contributorsMap["contributors[${index}][id]"] = "${contributor.id}"
contributorsMap["contributors[${index}][role]"] = contributor.role
}
Then updated my function parameter to @PartMap instead
@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:
Use @Field
@Field("contributors[]") contributors: MutableList<Contributor>
回答3:
You can use @partMap
@PartMap() Map<String, List<Contributor>> contibutors
来源:https://stackoverflow.com/questions/58949477/how-to-send-array-of-objects-in-retrofit-multipart-request