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

时间:2017-08-31 09:19:57

标签: 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}

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

对其进行格式化并以String而不是List<Map<String,String>>发布,因为改造始终会将地图转换为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>>