Android Retrofit - 将对象列表作为关联数组传递

标签 android retrofit

我有一个 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/

相关文章:

android - 使用 Google Play 游戏服务向排行榜提交分数

java - Android应用程序停止变量重置-生命周期

android - 我应该如何使用改造来获取数组下的图像

android - 无法为类型为 org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler 的对象获取未知属性 'okhttpVersion'

java - 为什么不调用改造 validator ?

java - Android 测试 - Robolectric + Mockito + Retrofit 出现 Wanted 但未调用错误

android - 渐变在 Android M 上因 IllegalArgumentException 而崩溃

Android Studio 无法在 Ubuntu 上启动

android - 如何使用 Retrofit 添加 TLS v 1.0 和 TLS v.1.1

android - 如何删除android Ice Cream Sandwich 中的软按钮/菜单?