2017-08-31 109 views
1

我有希望作爲輸入的運動類型的API:Android的改造 - 傳遞對象的列表作爲關聯數組

exercises[0][duration]=10 
exercises[0][type]=jump 
exercises[1][duration]=20 
exercises[1][type]=roll 

在Android方面,我一直在使用我的改造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}

+0

我會通過一個簡單的 「演習」

如下您可以將其轉換以JSON格式列出,而不是地圖。一旦你將它作爲JSON檢索,這種格式看起來很容易處理數組:「Exercises」:[{「duration」...},{...}] – Ricardo

+0

我無法控制API。我必須使用這種格式。 –

+0

請檢查此答案https://stackoverflow.com/questions/37698715/how-to-send-arrays-lists-with-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) 
+0

哦,它存在!,我剛剛發佈原始方式來做到這一點:) –

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>>