【问题标题】:Android Retrofit - Pass list of objects as associative arrayAndroid Retrofit - 将对象列表作为关联数组传递
【发布时间】:2017-08-31 18:06:37
【问题描述】:

我有一个 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}&amp;exercises[]={duration:20, type=roll}

【问题讨论】:

  • 我会以 JSON 格式传递一个简单的“练习”列表,而不是作为地图。将其作为 JSON 检索后,这种格式看起来很容易处理为数组:"exercises":[{"duration"...},{...}]
  • 我无法控制 API。我必须使用那种格式。
  • 知道了。是@FieldMap(见下面自己的答案)

标签: android retrofit


【解决方案1】:

我正在寻找的是@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)

【讨论】:

  • 哦,它存在!,我刚刚发布了这样做的原始方法:)
【解决方案2】:

将其格式化并发布为String 而不是List&lt;Map&lt;String,String&gt;&gt;,因为改造总是将地图转换为 json。

你可以这样转换:

        Exercise[] exercises = new Exercise[2];
        exercises[0] = new Exercise(10, "jump");
        exercises[1] = new Exercise(20, "roll");

        String postString = "";

        for(int i = 0; i < exercises.length; i++) {

            Exercise ex = exercises[i];
            postString += "exercises[" + i +"][duration]=" + ex.duration + "\n";
            postString += "exercises[" + i +"][type]=" + ex.type + "\n";
        }

        System.out.println(postString);

练习课:

    class Exercise {

        public Exercise(int duration, String type) {

            this.duration = duration;
            this.type = type;
        }

        int duration;
        String type;
    }

您的 API 函数将如下所示:

@FormUrlEncoded
@POST("api/v1/patient/{id}/workout")
fun addPatientWorkout(@Path("id") id: Long,
                      @Field("title") title: String,
                      @Field("exercises"): exercises, String)
        : Single<Response<Workout>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2018-02-10
    • 1970-01-01
    • 2019-03-27
    • 2021-11-12
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多