我有一个 API,它需要一个练习列表作为输入:
exercises[0][duration]=10
exercises[0][type]=jump
exercises[1][duration]=20
exercises[1][type]=roll
在 Android 端,我使用 Retrofit 构建了我的 API 类。
如何传递我的 List<Exercise>
到 API 方法以获得上述参数。
目前尝试过:
@FormUrlEncoded
@POST("api/v1/patient/{id}/workout")
fun addPatientWorkout(@Path("id") id: Long,
@Field("title") title: String,
@Field("exercises[]") exercises: List<Map<String,String>>)
: Single<Response<Workout>>
但这并没有达到我的预期。相反:
exercises[]={duration:10, type=jump}&exercises[]={duration:20, type=roll}
最佳答案
我一直在寻找的是 @FieldMap
注释。这允许构建名称/值映射以作为 POST 参数传递。
@FormUrlEncoded
@POST("api/v1/patient/{id}/workout")
fun addPatientWorkout(@Path("id") id: Long,
@Field("title") title: String,
@FieldMap exercises: Map<String,String>)
: Single<Response<Workout>>
然后使用以下代码调用:
val exerciseFields: MutableMap<String, String> = mutableMapOf()
workout.exercises.forEachIndexed { index, exercise ->
exerciseFields["exercises[$index][duration]"] = exercise.duration.toString()
exerciseFields["exercises[$index][type]"] =exercise.type.name.toLowerCase()
}
return addPatientWorkout(
workout.patient?.id ?: -1,
workout.title,
exerciseFields)
关于Android Retrofit - 将对象列表作为关联数组传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45977800/